Know THIS Python List Tip!!

  Рет қаралды 441,661

b001

b001

Күн бұрын

⭐ Join the Byte Club to practice your Python skills! ($2.99/mo): / @b001
🐦 Follow me on Twitter: / b001io
In this short, I explain how to use the index method, the pop method, and the insert method to remove an item from a list and place it at the front of the list.
Background Music:
Stardrive by | e s c p | escp-music.ban...
Music promoted by www.free-stock...
Creative Commons / Attribution 4.0 International (CC BY 4.0)
creativecommon...

Пікірлер: 308
@petrlaskevic1948
@petrlaskevic1948 Жыл бұрын
It would be so much better to store an int with the index of the used item, and use that instead of shuffling the array around.
@gregcarlson8438
@gregcarlson8438 Жыл бұрын
This is what I was thinking
@houmy9041
@houmy9041 Жыл бұрын
You mean like an enum
@cctz_1
@cctz_1 Жыл бұрын
Can you explain a little bit please ? Sorry im new to coding and want to understand
@petrlaskevic1948
@petrlaskevic1948 Жыл бұрын
@@cctz_1 Learn how to use arrays/lists
@Lllllluuj
@Lllllluuj Жыл бұрын
@@cctz_1 basically he is saying that you can enumerate the list, which allows for the items to have a number associated with it (index) and you can just use the indexed number with the sword to call it, instead of having to move sword to 0
@shiinondogewalker2809
@shiinondogewalker2809 Жыл бұрын
I'm just thinking why you'd want the items to move around on the hotbar instead of highlighting which is selected
@MsWhiskey974
@MsWhiskey974 Жыл бұрын
Then if you add or remove an item from the hotbar, you will also need to offset the list cursor used for highlighting. This can be avoided if list has fixed size and stores empty slots somehow. Again, I guess there are lots of ways to achieve a hotbar, some saner than others xD
@shiinondogewalker2809
@shiinondogewalker2809 Жыл бұрын
@@MsWhiskey974 right, I'd think an array for the hotbar plus an int which specifies which is selected would be a good approach
@MsWhiskey974
@MsWhiskey974 Жыл бұрын
@@shiinondogewalker2809 I’d probably go with that as well. That way, you can have empty slots which is pretty common for game hotbars and items won’t move around which is less error prone.
@fishingmasterxy
@fishingmasterxy Жыл бұрын
hashmap that stores linked nodes would work for frequent switching of items if you use the item name as the key. and have a reference to the head of the list. constant time operations. for switching and finding the value
@erinmutchler3612
@erinmutchler3612 Жыл бұрын
Yeah I was gonna say. Isn’t insert() linear time? I feel like a linked list would be much better. Or heck, even a growable array and then use the last element of the array as the item in the players hand
@fishingmasterxy
@fishingmasterxy Жыл бұрын
@@erinmutchler3612 yeah, hashmap for finding the value to switch, the value being a linked node. constant time to find the item, constant time to do the switch
@arielguzman2875
@arielguzman2875 Жыл бұрын
This should be the preferred method to be efficient. Likely rethink the need for a list for this op.
@mattmurphy7030
@mattmurphy7030 2 ай бұрын
A hash map for 10 items is next level stupid first year coder mistake
@fishingmasterxy
@fishingmasterxy 2 ай бұрын
@@mattmurphy7030 For small inputs yeah. I was giving theoretical O(N) for the algo for any size N
@phantompayne8248
@phantompayne8248 Ай бұрын
The bgm is soo good!!
@troybaxter
@troybaxter Жыл бұрын
You can continue this logic further and request the items you want to swap. Just add these lines: try: temphb = list(map(str.lower, hotbar) item = input(“Item 1: “) index1 = temphb.index(item) try: swapItem = input(“Item 2: “) index2 = temphb.index(swapItem) hotbar[index1], hotbar[index2] = hotbar[index2], hotbar[index1] print(hotbar) except: print(“Item Doesn’t in Hotbar to Swap With”) except: print(“That item isn’t in your hotbar”) Throw in a couple try-except lines, a while loop, and you have a fully functioning hotbar swapping program
@troybaxter
@troybaxter Жыл бұрын
@Man Aquatic where did I make a mistake? I’ll edit it if needed.
@yungmaz13
@yungmaz13 Жыл бұрын
@@troybaxter I think Man Aquatic is confused because of the indentation
@troybaxter
@troybaxter Жыл бұрын
@@yungmaz13 yeah, blame KZbin on that.
@yungmaz13
@yungmaz13 Жыл бұрын
@@troybaxter Lmao, you could use spaces to indent
@troybaxter
@troybaxter Жыл бұрын
@@yungmaz13 the problem is that it is weird on the phone or on notifications.
@POWERSID17
@POWERSID17 2 ай бұрын
You should make a playlist of full python course. ❤
@alexhernandez8550
@alexhernandez8550 Жыл бұрын
Would recommend also using a json to structure your game inventory
@eyebol
@eyebol Жыл бұрын
do you mean a dictionary?
@Hex-Scholar
@Hex-Scholar Жыл бұрын
list = ["sword", "bow", "axe"] list[list.index("axe")], list[0] = list[0], list[list.index("axe")]
@epsi
@epsi Жыл бұрын
Slightly inefficient due to calling list.index twice. If using Python 3.8 or newer, you can abuse the walrus operator: list[i], list[0] = list[0], list[(i := list.index("axe"))] I call it abuse because it's not exactly intuitive. For example, this alternative attempt is incorrect: list[(i := list.index("axe"))], list[0] = list[0], list[i]
@Hex-Scholar
@Hex-Scholar Жыл бұрын
@@epsi Thanks, yes the complexity of my code will be 2*n, in the worst-case, to keep it n, I could first find the index and store it inside a variable and then go for the swap, but what is the fun in that 😅 As for the walrus operator, I have studied about it, but not really used it that often. Also, I was trying to do this too: list[(i := list.index("axe"))], list[0] = list[0], list[i] Apparently it doesn't work :(
@mousepotatoliteratureclub
@mousepotatoliteratureclub Жыл бұрын
@@epsi True, but if your list is long enough/your items complex enough for this to cause performance issues, you should be using something more efficient than O(n) index lookup anyway.
@epsi
@epsi Жыл бұрын
@@mousepotatoliteratureclub Definitely agree. Just wanted to point out the walrus operator's utility here to reduce the time complexity of a "simple" assignment from O(2n) to O(n).
@Евгений-р7р3ф
@Евгений-р7р3ф Жыл бұрын
@@Hex-Scholar, It happens because of the time of compiling pieces of your code. In case of assigning operator it works left-to-right order. The right-to-left compiling string of the code must not exist since your should evaluate the data which you're assigning to the variable first and then assign that.
@Tripicality
@Tripicality Жыл бұрын
Helpful video, but those flickering green subtitles are very uncomfortable to look at
@b001
@b001 Жыл бұрын
I agree. I wanted to try it out, but I dont think they work well with my shorts. You can’t read subtitles and look at code at the same time. Likely won’t add them again. Thanks for the feedback!
@samuelpacheco1222
@samuelpacheco1222 Жыл бұрын
A O(1) solution: Transform every item to a constant number (enumerated enums) Torch = 1 Rock = 2 Potion = 3 Sword = 4 Shield = 5 And create an unordered_map of pointers such as a[index] = index So we know that for a[1] = 1 and that means a[torch] = 1 // torch is in slot 1! Swaps become constants Sword = 4 Torch = 1 a[1] = a[4] // first bucket nows points to index 4 This is the same as a[torch] = a[sword] // torch now it’s wherever sword currently is Then lastly a[4] = 1 a[sword] = 1 // this is telling sword points to position 1 Memory is O(N) (you only need the pointers array) Swaps O(1) As en excercise: how to reconstruct the array in order from the pointer array in O(N)?
@sebastiangudino9377
@sebastiangudino9377 Жыл бұрын
This is the correct solution. In thid contects the values of the enum are an ID. This is a very common pattern in games where you have a lookup table of all items. And you just work with the ID's instead (Never copying, never moving, basicaly pointers)
@mattmurphy7030
@mattmurphy7030 2 ай бұрын
Using a map for 10 items is the dumbest solution you could have come up with
@pandalonium
@pandalonium Ай бұрын
I genuinely thought you were going to show how you can do all of that in one line
@edizdogankarakoc7768
@edizdogankarakoc7768 Жыл бұрын
Wouldn't it be more compact if we connected 8th and 9th line by typing: hotbar.remove("Sword") hotbar.insert(0, "Sword") print(hotbar) ------------------------------------------------ Please correct me if I'm wrong.
@panosmpasiourasserrano7449
@panosmpasiourasserrano7449 9 ай бұрын
You might have multiple swords in your hotbar
@ferretdevshit2838
@ferretdevshit2838 Жыл бұрын
for my fellow one line freaks: hotbar = [x for x in ["Sword",*hotbar] if x != "Sword"] effiency depends on the amount of items in the inventory, would be faster if the list if small but much less efficient if ur user can have like 5 billion items as its still a for loop apart from that, the same functionality can also be one-lined easily as the pop method returns the item, giving us hotbar.insert(0, hotbar.pop("Sword"))
@juhotuho10
@juhotuho10 Жыл бұрын
cool tutorial, but oh man is that a terrible way to implement a hotbar
@imvine
@imvine 10 ай бұрын
Wait Wait wait it just moves the list instead of overwriting Torch Is that what pop does?
@lillii9119
@lillii9119 9 ай бұрын
That's the "insert". list.insert(0, x) will shift all items before inserting in index 0. If you want to overwrite you need list[0] = x
@Loading_Code
@Loading_Code Жыл бұрын
Wow bro❤
@ScienceWorldz
@ScienceWorldz Жыл бұрын
We can combine all those lines into..... hotbar.insert(0, hotbar.pop(hotbar.index("Sword")))
@clipstobingeon
@clipstobingeon Жыл бұрын
❤❤❤❤
@ehudkotegaro
@ehudkotegaro 9 ай бұрын
Both pop and insert are potentially pretty expensive. Can't you just l[index],l[0]=l[0],l[insert]?
@mohammedvaseem3331
@mohammedvaseem3331 8 ай бұрын
Theme?
@massy-3961
@massy-3961 Жыл бұрын
O(3N) solution lmfao
@raymondarrington5339
@raymondarrington5339 Жыл бұрын
O(N)
@HowaboutNope-uh2yx
@HowaboutNope-uh2yx Жыл бұрын
Bro, first of all you don't know how big O notation works, second, you can't solve this problem faster than O(N).
@BlueSky-fj7yi
@BlueSky-fj7yi Жыл бұрын
Thats not how it works 😨
@massy-3961
@massy-3961 Жыл бұрын
@@HowaboutNope-uh2yx just because you can’t solve it better than O(N) doesn’t mean you should take O(3N) solution when it could legitimately be O(1N), not to mention you most certainly can if you use the right data structure for the task, which an array is most certainly not the right data structure for making modifications on the front. Not to mention you can actually do this better than O(N) on average with worse case being O(N) even with an array.
@FlorianWendelborn
@FlorianWendelborn Жыл бұрын
@@massy-3961 O(3n) is the same thing as O(n)
@pavelpetkov8092
@pavelpetkov8092 Жыл бұрын
hotbar = deque(hotbar) while hotbar[0] != wanted_item: hotbar.append(hotbar.popleft())
@christophsiebert1213
@christophsiebert1213 Жыл бұрын
What the actual heck. And I thought ot couldn't beany worse
@KASANITEJ
@KASANITEJ Жыл бұрын
Dont do that. Just 0th index element with sword index
@imademedikasurya3917
@imademedikasurya3917 Жыл бұрын
My during programing: *Pop, sort, insert, and index is not allowed make your own version...*
@elgoogssie3969
@elgoogssie3969 11 ай бұрын
It can be done much better using less code using other language.
@Anast_alma
@Anast_alma Жыл бұрын
How do you write everything so fast?
@theworlddiscoverer7316
@theworlddiscoverer7316 Жыл бұрын
he dosent he skips the part where he types
@Anast_alma
@Anast_alma Жыл бұрын
@@theworlddiscoverer7316 oh ok
@thunderskull258
@thunderskull258 Жыл бұрын
Just use remove and append
@christophsiebert1213
@christophsiebert1213 Жыл бұрын
Or swap the two items directly
@moshadoe
@moshadoe Жыл бұрын
I'm not too sure which would be preferred, but it seems like a dictionary would come in handy here, where you can specify the equip spots as your keys, then change the value of that key-value pairing. That way, you never really care where the item is, just that you replace the current item with the desired one, as a sort of bonus idea, check if the original value was assigned to an inventory space, and if so place it in that specific spot. If anyone knows why that's not a good idea, feel free to inform me. :)
@thekaikage
@thekaikage Жыл бұрын
What extension do you use for python?
@yungmaz13
@yungmaz13 Жыл бұрын
I assume you’re talking about the VSCode extension? If so then the extension is literally just called python
@harisjaved1379
@harisjaved1379 Жыл бұрын
Another way Hotbar[3], Hotbar[0] = Hotbar[0], Hotbar[3]
@b001
@b001 Жыл бұрын
The list will not always be in the same order, so you won’t know the index of ‘Sword’ in the list.
@harisjaved1379
@harisjaved1379 Жыл бұрын
@@b001 yes that’s true
@NiceO1
@NiceO1 10 ай бұрын
quite new to Programing and i just wanted to ask if the words being typed instantly is cause you just did ctrl+v or if theres some feature i don't know about
@production-code
@production-code 2 ай бұрын
A game in python ? Hmmmm....
@paramvirsingh5640
@paramvirsingh5640 Жыл бұрын
Or just swap the two indices
@lostgoat
@lostgoat Жыл бұрын
Good lord why
@creeptitan
@creeptitan Жыл бұрын
List pops are very slow though
@erdemisitan
@erdemisitan Жыл бұрын
Guys I need ur help: pycharm or vscode for coding python?
@TheBurntHoney
@TheBurntHoney Жыл бұрын
I suggest pycharm. Theres an comm/edu version and with student license you get premium. Jetbrains with the new ui is pretty powerful and debugging is much easier in pycharm compared to vscode.
@Skirmisher986
@Skirmisher986 Жыл бұрын
I also would recommend pycharm, as it has a really nice integration with git
@lucsoft
@lucsoft Жыл бұрын
In real code just use a map instead way simpler
@Andrey-rc6wp
@Andrey-rc6wp Жыл бұрын
Here's the code if you just want to swap the items instead of shifting them like in the video: hotbar[3], hotbar [0] = hotbar[0], hotbar [3]
@championxxlNL
@championxxlNL Жыл бұрын
This isn't necessary more efficient and I'd say becomes less readable when the program grows
@rksmehul
@rksmehul Жыл бұрын
@@championxxlNL O(1) vs O(n)
@geoafrikana
@geoafrikana Жыл бұрын
​@@rksmehul This solution assumes that you know the index of the item which isn't the case.
@rksmehul
@rksmehul Жыл бұрын
@@geoafrikana yup, didn’t think it through!
@pramodvreddy21
@pramodvreddy21 Жыл бұрын
​@@geoafrikana in that case, you can use index(item) inside the index of list
@mori7423
@mori7423 Жыл бұрын
That's so simple but then I think how many operations are being done on the hardware side to perform these actions. I always wonder if there's a faster way
@electrocaruzo-karpada2485
@electrocaruzo-karpada2485 Жыл бұрын
You could just store the item that's popped in a variable and not pop it...
@mori7423
@mori7423 Жыл бұрын
@@electrocaruzo-karpada2485 true. I was also solving some quite difficult exercises using visual basic back in the day where we had to solve the exercises using as little variables as possible
@samcousins3204
@samcousins3204 Жыл бұрын
please look into Data Structures & Algorithms!! Basic one of ur first couple classes which will answer this exact question:)
@datboi1861
@datboi1861 Жыл бұрын
​@@samcousins3204 This is the universe's way of getting me to finally look into DSA. Thank you, stranger.
@samcousins3204
@samcousins3204 Жыл бұрын
@@datboi1861 Glad I could help:) i remember feeling really hopeful when i realized that coding, a hobby interest, could be supercharged with real academic thought
@siriusblack9999
@siriusblack9999 Жыл бұрын
yaaay great, and your hotbar is also shuffled so your torch moves from your hand to slot 1, your rock moves from slot 1 to slot 2, and your potion moves from slot 2 to slot 3 instead of pop/insert, you actually want want to use hotbar[0], hotbar[index] = hotbar[index], hotbar[0] to swap only the sword and torch
@Shellll
@Shellll Ай бұрын
Ty, as a beginner I was thinking something looked weird about this solution. Much more elegant
@afailable
@afailable Жыл бұрын
Surely an index swap would make more sense? I'm used to languages like c or c++, so it seems crazy to pop and insert on a list when you can swap references...
@jaysonbunnell8097
@jaysonbunnell8097 Жыл бұрын
That’s likely the best solution. Python has a syntactic sugar for that case: hotbar[0], hotbar[index] = hotbar[index], hotbar[0]. Odd enough methodology from OC, but good for beginners to know those operations exist
@Oscar-vs5yw
@Oscar-vs5yw Жыл бұрын
I mostly work in python and I completely agree with u
@psykozz7385
@psykozz7385 Жыл бұрын
How would you do it in C++? That's interesting to me, if you don't mind
@SpoorloosDev
@SpoorloosDev 10 ай бұрын
@@psykozz7385 std::vector items{ "Hello", "World" }; std::swap(items[0], items[1]);
@xnaaloh4437
@xnaaloh4437 10 ай бұрын
⁠@@psykozz7385are you talking abt the index swap? If you are then you will need a temporary variable. Like so, char* tmp = hotbar[index]; hotbar[index] = hotbar[0]; hotbar[0] = tmp;
@IanRiley915
@IanRiley915 Жыл бұрын
Works but you should definitely swap them instead 😊
@silentlyow
@silentlyow Жыл бұрын
Swap? Take a second look and you understand that simple swap won't work. But what we can both agree with that it's piece of code none of us should ever write
@IanRiley915
@IanRiley915 Жыл бұрын
@@silentlyow You might need to elaborate further. The author is just using the 0 position of the list to represent the held item, so you can just `tmp=hotbar[0]`, `hotbar[0] = hotbar[index]`, `hotbar[index] = tmp`, which is a swap.
@aonodensetsu
@aonodensetsu Жыл бұрын
​@@IanRiley915in python you just do hotbar[index], hotbar[0] = hotbar[0], hotbar[index] no need for a temp var
@seriouce4832
@seriouce4832 Жыл бұрын
@@IanRiley915 your idea is simply giving a different result. apparently the task is to move sword to pos 0 and move the rest of the list behind by one (to make space for the sword). in your proposal everything stays besides torch.
@exilednivera
@exilednivera Жыл бұрын
I can't remember any hotbars that shuffles items instead of just changing index of active item.
@ABCABC-sw8mh
@ABCABC-sw8mh Жыл бұрын
it can be do easier
@FictionHubZA
@FictionHubZA 2 ай бұрын
If this was java I would have put it in an array and out a variable int in the array brackets. When a right button is pressed it increments and moves forward. When a left button is pressed it decrement and moves left.
@MominAhmed-y6w
@MominAhmed-y6w 9 ай бұрын
Could you stop using music in your videos? It disturbs me.
@HighTheir_
@HighTheir_ Жыл бұрын
How would you write the code to swap the items rather than push each one to the next position after popping?
@jamesbiggs4421
@jamesbiggs4421 Жыл бұрын
list[x], list[y] = list[y], list[x]
@epsi
@epsi Жыл бұрын
Assuming you know the item exists in the hotbar list (i.e. you know the index method will not raise a ValueError exception): index = hotbar.index('Sword') hotbar[0], hotbar[index] = hotbar[index], hotbar[0]
@gopallohar5534
@gopallohar5534 Жыл бұрын
Which VScode theme is that?
@Евгений-р7р3ф
@Евгений-р7р3ф Жыл бұрын
Looks like Dracula
@unimagin2ble
@unimagin2ble Жыл бұрын
why wouldn't you just change the current item index to the index of the item they selected
@isaacingleby8771
@isaacingleby8771 4 күн бұрын
This is a bad way to handle inventory, a class that can assign to .hand and remove previous items to a .inventory list would be way smoother
@CC-1.
@CC-1. Жыл бұрын
You said first of all the list should be in order But Acordingly to me First of all there should be a seprate var for this and if it's undefined than the first of array!
@sirsquirrel0
@sirsquirrel0 Ай бұрын
I listed to this on repeat whilst I digested the comments. 🤷🤭
@thegoodlifewatch
@thegoodlifewatch 9 ай бұрын
what theme are you using?
@retrokoh
@retrokoh 8 ай бұрын
Index swapping would be so mucb easier. IND = hotbar.index('sword') hotbar[0], hotbar[IND] = hotbar[IND], hotbar[0]
@xgorntv
@xgorntv 2 ай бұрын
i will never think of making a game in python.
@mohmaedtaoufikbaccar7567
@mohmaedtaoufikbaccar7567 Жыл бұрын
Result = [item, ...list.pop(item)]
@stephystuff2955
@stephystuff2955 Ай бұрын
Do you have to repeat this code for each item to be swiped out?
@MisterSnail1234
@MisterSnail1234 Ай бұрын
Please show more memes like this one they're top🥺
@Repulsion-kt3tx
@Repulsion-kt3tx Ай бұрын
If javascript then first push and then shift 😮‍💨
@smokedice
@smokedice Жыл бұрын
Why are you using character quotations instead of strings? I get that python is weird, but come on!
@drunkenfarmer2513
@drunkenfarmer2513 8 ай бұрын
All these wasted cpu cycles, its no wonder games are all laggy has shit these days
@YuraSuper2048
@YuraSuper2048 Жыл бұрын
i feel like this is not an efficient way
@Pandorarl
@Pandorarl Жыл бұрын
Bro hasnt heard of enums
@BHK0000
@BHK0000 2 ай бұрын
Don’t name a variable the name of a function…
@zataritamods7499
@zataritamods7499 Жыл бұрын
This is useful information, but a terrible use case.
@oktabramantio4709
@oktabramantio4709 Жыл бұрын
I've always known the .append() function but this is the first time I hear .insert() function. Guess you learn something new everyday
@kitebeachinnbeachinn2888
@kitebeachinnbeachinn2888 Жыл бұрын
it adds to a specific position.
@hikari1690
@hikari1690 Жыл бұрын
Why not unshift?
@wanderingwatcher3981
@wanderingwatcher3981 Жыл бұрын
ehm..., this is silly, just used the index itself
@oguzhantopaloglu9442
@oguzhantopaloglu9442 Жыл бұрын
_list = ["a", "b", "c", "d", "e"] def swap_two_elements(_list: list[str], e1: str, e2: str): _list[_list.index(e2)], _list[_list.index(e1)] = _list[_list.index(e1)], _list[_list.index(e2)] print(_list) # [a, b, c, d, e] swap_two_elements(_list, "a", "c") swap_two_elements(_list, "d", "e") print(_list) # [c, b, a, e, d]
@Евгений-р7р3ф
@Евгений-р7р3ф Жыл бұрын
No offense, but it's not the best way to change outer scope variables in the inner scope of a function body. Appropriate usage is returning changed objects from a function and then assign them to variables
@andrei_camilotto
@andrei_camilotto Жыл бұрын
Looks like a lot of unnecessary steps..
@MrJonas1995
@MrJonas1995 Жыл бұрын
How about switching the first one with the one you want?
@eyebol
@eyebol Жыл бұрын
why would you want to do that?
@christophsiebert1213
@christophsiebert1213 Жыл бұрын
​@@eyebol In the case this wasn't sarcastic: Because that's literally what this "tip" is about. Swapping the item in the first slot with any other slot. You don't have to modify the size of the list twice to just switch two elements.
@eyebol
@eyebol Жыл бұрын
@@christophsiebert1213 i aint reading allat
@thomasgraewe3122
@thomasgraewe3122 2 ай бұрын
How to make ai worse:
@JungKimrecruiter
@JungKimrecruiter 14 күн бұрын
Good stuff!
@tofaa3668
@tofaa3668 2 ай бұрын
terrible approach
@maheshm1225
@maheshm1225 8 ай бұрын
Sort by des to get 4 th first
@1010-w4d
@1010-w4d Жыл бұрын
Or just swap with the first
@camfunme
@camfunme Жыл бұрын
You don't need either of those variables: 1) index is only used once, and doesn't exceed line usage => hotbar.pop(hotbar.index('Sword')) 2) item you already know and are using to find the index... => hotbar.insert(0, 'Sword')
@loserguy777
@loserguy777 Жыл бұрын
Yeah but what about parametrizing it
@zero11010
@zero11010 2 ай бұрын
I'm sure all of this has been pointed out over and over. The linear pass through this isn't the end of the world. It's a small list. But, it's wasteful and easy to avoid. You can swap places, or just use a different data structure. Also, from a game mechanics perspective you usually really don't want things in a hotbar to change locations. Yeah? If you want to access your sword you would likely always want that sword to be found with button 4 (or whatever). You would want to avoid a situation where each time you change your equipped items now your inventory is potentially in a different order and you have to actually look to see what is where to equip the right item. This kinda ruins the functionality of a hotbar to begin with.
@mattmurphy7030
@mattmurphy7030 2 ай бұрын
Using a different data structure is next level autism. It’s 5 items. Use a list.
@kelvinxg6754
@kelvinxg6754 Жыл бұрын
Minecraft? For sure
@DevWaddle
@DevWaddle 9 ай бұрын
what theme is that?
@MrLazini
@MrLazini Жыл бұрын
This is suuuper slow
@6644guilherme
@6644guilherme Жыл бұрын
Very nice. Isnt there a way to get the item without removing it so i dont need to re insert it all the times? Like hotbar[0]
@awli8861
@awli8861 Жыл бұрын
there is but this guy is stupid
@algorithmic_mind
@algorithmic_mind Жыл бұрын
Theme name please
@egor.okhterov
@egor.okhterov Жыл бұрын
Use dict
@AhmedIbrahim-fi2so
@AhmedIbrahim-fi2so Жыл бұрын
to slow
@hardcopy95
@hardcopy95 Жыл бұрын
Why you use index as a variable name, isn't that frowned upon
@unimagin2ble
@unimagin2ble Жыл бұрын
easier for educational purposes
@alessandrodestasi7811
@alessandrodestasi7811 Жыл бұрын
hotbar.insert(0, hotbar.pop(hotbar.index(“Sword”)))
@abdelrhman..mohamed142
@abdelrhman..mohamed142 Жыл бұрын
@obinnaeke9663
@obinnaeke9663 10 ай бұрын
This is actually a great way to select the new item while maintaining the order of the list. Whe. Sword is selected, it moves to the top of the list and the order of the inventory remains the same. The swap method changes the order of the list
@AgencyProMax
@AgencyProMax 8 ай бұрын
genio
@nigh_anxiety
@nigh_anxiety Жыл бұрын
You can do a swap in a one-liner with the walrus operator: hotbar[ind], hotbar[0] = hotbar[0], hotbar[ind:=hotbar.index(item)] Of course, it should be wrapped in a Try/Except in case the target item can't be found.
@WarOfTheTorky
@WarOfTheTorky 10 ай бұрын
Nice list of methods I can use... I'm still learning, but I'll get there eventually.
@rohithchirumalla
@rohithchirumalla 10 ай бұрын
We can use remove function and then insert so that we dont need that index part
@hamadrehman853
@hamadrehman853 2 ай бұрын
this is an excellent way to teach about array methods.
@rysiexo
@rysiexo Жыл бұрын
I would go with Map, your example has too many operations.
@Kidneydawg
@Kidneydawg Жыл бұрын
Seems like a dictionary would do what you want way more easily
@elatedbento
@elatedbento Жыл бұрын
A dictionary wouldn't provide you with a sorted set of elements. At most, it would return you the elements sorted by insertion order.
@mattmurphy7030
@mattmurphy7030 2 ай бұрын
A dictionary for 5 items is the stupidest thing you could have said
@lol-kb8hz
@lol-kb8hz Жыл бұрын
its incredibly inefficient to do it that way
@seyproductions
@seyproductions 9 ай бұрын
Cool, now my players can slice cakes with a sword.
@xiangzhang5279
@xiangzhang5279 Жыл бұрын
You don't want to name any variable as "index"
@animus8343
@animus8343 Жыл бұрын
Hey sir, how to change my text color like yours
5 Good Python Habits
17:35
Indently
Рет қаралды 541 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 164 М.
Watermelon magic box! #shorts by Leisi Crazy
00:20
Leisi Crazy
Рет қаралды 14 МЛН
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,1 МЛН
The Fastest Prime Number Algorithm
5:23
MarshySyntax
Рет қаралды 3,2 М.
25 nooby Python habits you need to ditch
9:12
mCoding
Рет қаралды 1,8 МЛН
Coding Was HARD Until I Learned These 5 Things...
8:34
Elsa Scola
Рет қаралды 485 М.
My 10 “Clean” Code Principles (Start These Now)
15:12
Conner Ardman
Рет қаралды 230 М.
How To Write Better Functions In Python
14:17
Indently
Рет қаралды 26 М.
10 Python Comprehensions You SHOULD Be Using
21:35
Tech With Tim
Рет қаралды 148 М.
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,7 МЛН
THIS is Why List Comprehension is SO Efficient!
5:25
b001
Рет қаралды 172 М.