Тёмный

❌ DON'T use a for loop like this for multiple Lists in Python!!! 

Patrick Loeber
Подписаться 268 тыс.
Просмотров 504 тыс.
50% 1

Don't use a for loop like this for multiple Lists in Python! Instead use the handy zip() function!
Find Python jobs: pythonengineer.pallet.com
⭐ Join Our Discord : / discord
📓 ML Notebooks available on Patreon:
/ patrickloeber
If you enjoyed this video, please subscribe to the channel:
▶️ : / @patloeber
~~~~~~~~~~~~~~~ CONNECT ~~~~~~~~~~~~~~~
🖥️ Website: www.python-engineer.com
🐦 Twitter - / patloeber
✉️ Newsletter - www.python-engineer.com/newsl...
📸 Instagram - / patloeber
🦾 Discord: / discord
▶️ Subscribe: / @patloeber
~~~~~~~~~~~~~~ SUPPORT ME ~~~~~~~~~~~~~~
🅿 Patreon - / patrickloeber
#Python

Опубликовано:

 

13 апр 2022

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 234   
@patloeber
@patloeber Год назад
Find Python jobs: pythonengineer.pallet.com
@RishiDsouza
@RishiDsouza Год назад
Where are u doing this?
@ArmirMitrandir
@ArmirMitrandir 2 года назад
for i in range(min(len(a),len(b)))
@vinpepper1384
@vinpepper1384 2 года назад
Fuck that too many parenthesis
@Alec9821
@Alec9821 2 года назад
Thank you for this, much more efficient. I was gonna comment it but you beat me to it 😁
@marcelocosta9620
@marcelocosta9620 2 года назад
I think this is more readable.
@simonchong7514
@simonchong7514 2 года назад
@@ymaneboubleh3798 Flutter? fuck off of that, i hate it so much
@neoesm
@neoesm 2 года назад
# More readable safeRange = min(len(a),len(b)) for index in range(safeRange):
@davidc.890
@davidc.890 2 года назад
There is also itertools.zip_longest() to fill-in missing values in uneven iterables
@almajulio5842
@almajulio5842 2 года назад
thanks
@ziga1122
@ziga1122 2 года назад
I wish i knew this before the exam, i zipped 2 arrays and 1 was longer so the last value of the longer one was ignored and the tests didnt pass 🥲
@userou-ig1ze
@userou-ig1ze 2 года назад
I like these videos. I always ignore the suggestions in the video and go to the comments for the correct/better solution.
@mechtist
@mechtist Год назад
savage but valid
@schlopping
@schlopping Год назад
This is a rare case where the video solution is actually the best
@higheloguy9057
@higheloguy9057 2 года назад
Also zip has an arguemnt where it can throw an error if the amount of elements is not equal.
@cristianoo2
@cristianoo2 2 года назад
Which makes it work just like the first option which zip was supposed to "replace". So, not a good tip after all
@monochromeart7311
@monochromeart7311 2 года назад
@@cristianoo2 you're incorrect. The optional argument for throwing an error makes it explicit that if 1 is longer you'd have to handle an error, and you'd also have more specific information.
@dayansiddiqui4426
@dayansiddiqui4426 2 года назад
@@cristianoo2 failing loudly, predictably, and descriptively on invalid inputs is often very important and desirable. the original option will not throw an error if the index you iter through is of the shorter list, zip will handle that scenario
@NateROCKS112
@NateROCKS112 2 года назад
@@cristianoo2 alongside what the others said, it'd also throw an error _before_ you try to loop, so you don't accidentally do processing on invalid inputs.
@eadweard.
@eadweard. 2 года назад
If you're on python 3.10 you can use the strict=True keyword to ensure your code raises if your lists are of unequal length.
@nindocomic
@nindocomic Год назад
Oh I didn't know this, thank you! I was just about to comment that in most cases (I) do this, unequal lenght arrays usually means theres some sort of data error and raising should be done.
@patrick4406
@patrick4406 2 года назад
Sometimes an error safes a lot of time searching for the reason of strange results 🤪
@dylan-dylan-dylan
@dylan-dylan-dylan Год назад
THANK YOU! For a similar reason I never use .get with dictionaries. If I inadvertently use an invalid key, I don’t want the interpreter to just put in a filler value such as None - that’s how you get bad analysis with perfectly good data as many mathematical functions simply ignore None. Or, in non-statistical contexts, substituting None will likely cause a type error downstream anyway.
@AnyVideo999
@AnyVideo999 2 года назад
While useful, often there is some sort of error if two lists which should be accessed in pairs have differing lengths.
@mohammadkeifary2009
@mohammadkeifary2009 Год назад
Really liked the idea of quick learning tips videos like this. Big thumbs up.
@guidosalescalvano9862
@guidosalescalvano9862 Год назад
You don't want it to stop at the shortest sequence, you want it to raise an exception.
@mahdi-hasan
@mahdi-hasan Год назад
thank you so much, i was looking for this
@taloki8738
@taloki8738 Год назад
This is awesome, you got yourself a new subscriber.
@hadawardgz
@hadawardgz 2 года назад
Nice tip
@phipag1997
@phipag1997 2 года назад
Didn’t know it stops for the shortest sequence. Nice.
@Roman-rs6um
@Roman-rs6um Год назад
Dude that's rly helpful for beginners! I appreciate your job!
@junyooor7582
@junyooor7582 2 года назад
thank you big help! looking for this in a long time
@hn1f
@hn1f Год назад
Another way: a = [1,2,3,4] b = ["spam","eggs","spam-sushi"] for i in range(len(a)): try: print(a[i], b[i]) except: pass
@imfrommars7362
@imfrommars7362 10 месяцев назад
a = [1, 2, 3, 4] b = ['one', 'two', 'three', 'four', 'five'] for x in range(min(len(a), len(b))): print(a[x], b[x])
@AshishRanjan-jn7re
@AshishRanjan-jn7re Год назад
Now you can set "strict=True" in zip() to enforce same length criteria.
@sankalpmane9029
@sankalpmane9029 2 года назад
Didn't know that. Thanks🙌
@drkings2055
@drkings2055 2 года назад
i needed this
@kastannie9045
@kastannie9045 9 месяцев назад
looked for this the whole day lmao
@eternablue730
@eternablue730 2 года назад
simpely do for i in range(min(len(a), len(b))) using the index is much better for algorithms, how do you access the next value or the one before if you can't use a[i-1]
@vns1956
@vns1956 2 года назад
you can use enumerate for that
@michaelthornes
@michaelthornes 2 года назад
@@vns1956 zip uses more memory so it's worth just using indices
@vns1956
@vns1956 2 года назад
@@michaelthornes I disagree. Using range(len(x)) is almost always not needed. Python provides more readable methods and list comprehensions, that are not only more beautiful and readable, but also less error prone.
@loganclark3642
@loganclark3642 2 года назад
Just so you know, the audio seems pretty loud in my headphones. You might need to mix it down a little bit!
@lorenzobarone45
@lorenzobarone45 2 года назад
you can also use enumerate()
@USELESSFACTSDAILYDAY
@USELESSFACTSDAILYDAY 2 года назад
Nice little tip 😁
@sarahjamal86
@sarahjamal86 2 года назад
I love theses videos I watch them for fun and knowledge 🤩
@yan2410
@yan2410 Год назад
Thank you sir
@Tennisbull-match-statistics
@Tennisbull-match-statistics 2 года назад
Those short tips are great! 🙏
@newsjuice7404
@newsjuice7404 2 года назад
You absolutely amazing I love your clips
@DarkSolidity
@DarkSolidity 2 года назад
list_a = [1, 2, 3] list_b = [“one”, “two”, “three”] list_of_tuple = list(zip(list_a, list_b)) for count, item in enumerate(list_of_tuple, 1): val_a, val_b = item print(’Item #: {count}, ‘value a:’, val_a, ‘value b:’, val_b) This probably isn’t the best way as this adds 2 extra lines of code but it’s probably my favorite way to do this.
@nonono6400
@nonono6400 2 года назад
Funny you bring that up. So proud of my janky python hahaha
@axospyeyes281
@axospyeyes281 Год назад
this is what I've been looking forrrr
@juriwerth
@juriwerth 2 года назад
thank you
@gavincoulson3900
@gavincoulson3900 2 года назад
Great content
@musclechicken9036
@musclechicken9036 2 года назад
If it’s specifically for printing the index of the item on the list you could just do: for i in range(len(a)) print(i, a[i]) And a would be only one list, there would be no need for a second list Edit: I am stupid
@ytechnology
@ytechnology 2 года назад
A long time ago, whenever I worked with multiple parallel lists, I ended them with something, usually a NULL. This was with the C language, but it's nice to see how modern languages have improved to address an old problem.
@MarineroAndroid
@MarineroAndroid 2 года назад
It's still true with C language,
@christopherdyson1158
@christopherdyson1158 Год назад
I used to do stuff like this back when I started programming... only later realized that if I'm programming it for myself, I most likely already have them the same length and its just extra computations that are unneeded and make it slightly less efficient (which may add up it I call that function 100s or 1000s of times though admittedly its fine for things that dont run as much). Just document that the method assumes the inputs are of equal length.
@brandonallen2301
@brandonallen2301 2 года назад
thank's bro
@tankhaiinh1729
@tankhaiinh1729 2 года назад
thanks
@InTranceofficial
@InTranceofficial 2 года назад
this is awesome 😎👍
@BigCreep
@BigCreep Год назад
The first way failed with a traceable error, the second failed silently?
@gonzalotoloza6700
@gonzalotoloza6700 Год назад
simpler for i, numbers in enumerate(b, 1): print(f”{i}: {numbers}”)
@xpita0_041
@xpita0_041 Год назад
a = [1,2,3] b = ['one','two','three'] for i in range (0,3): print (a[i], b[i])
@kotsmile
@kotsmile 2 года назад
Can you say name of your vscode theme?
@its_code
@its_code 2 года назад
Really helpful 😍😍💕💕❤️
@juanpunch8473
@juanpunch8473 Год назад
Thankss!
@Sameer-rd5fm
@Sameer-rd5fm Год назад
u r my fav python teacher
@David-IoanStanescu47
@David-IoanStanescu47 Год назад
You could use 2 for loops with either of the methods: for i in range(len(a)): for j in range(len(b)): Or for elem in a: for elem_2 in b:
@solidzack
@solidzack Год назад
That'd give you the cross product, which we don't want here. We want to access the items in pairs
@arekxv
@arekxv 2 года назад
Dont do this because its less "error prone". This error is GOOD to happen because you will find about it and fix it fast. If you do the zip for this and you dont figure out that the second list is shorter it could be MONTHS or even YEARS of bad data stored i databases before you find out about the issue. Now tell me, which of those errors is easier to fix?
@jacobharmon6162
@jacobharmon6162 2 года назад
Enumerate >> zip for idx, val in enumerate(b): print(f’{idx} {val}’)
@parampatel8853
@parampatel8853 2 года назад
Which theme u use?
@rohitghosh475
@rohitghosh475 Год назад
For the next video please complete the topic lists in tuple
@solidzack
@solidzack Год назад
While I do use zip to create value pairs, I didn't know about this behavior, which is actually really bad. If you wanna access two lists as tuples that usually means these values share some dependency and you want a pair for each element. So if one list is shorter than the other then usually something went wrong. And by default zip just ignores all the remaining elements of the longer lists which could lead to confusing results as values you expected to appear are suddenly missing. Zip should throw an exception by default too
@No_Underscore
@No_Underscore 2 года назад
Thx!
@SupreemeSteevee
@SupreemeSteevee 2 месяца назад
You can also use enumarate
@aaskrad
@aaskrad Год назад
you can also: for index, value in zip(range(len(iter)), iter): ...
@juniorjvn
@juniorjvn 2 года назад
Well, if you use the first list to enumerate the items in list b, you can use this code for i, val in enumerate(b, start=1): print(i, val) output: 1 one 2 two 3 three
@NoProblem76
@NoProblem76 2 года назад
Ah... RIP izip
@vadivelan4228
@vadivelan4228 2 года назад
Thanks
@ericoschmitt
@ericoschmitt Год назад
Nice!
@shaheryarsohail9675
@shaheryarsohail9675 2 года назад
This is actually extremely stupid. The zip function actually makes a new list so for one thing, you're allocating more memory (higher memory usage). For another thing, you lose the ability to go to the next/previous element in the same iteration. Better way is to use: for i in range(min(len(a), len(b))): .... This way would also eliminate the chances of that. Please stop recommending learning programmers bad practices.
@cristianoo2
@cristianoo2 2 года назад
Yes, and also you add a unintented behavior to the algorithm... If it's a function that supposedly is expecting two equal lists, that's what the program must have. If not, an exception need to be raised. This recommendation is bad coding.
@nigh_anxiety
@nigh_anxiety 2 года назад
zip() does not create a new list. it creates an iterator objext which outputs tuples. obviously, if you need your loop to access other elements in your iterables this is the wrong approach, but if you have a need to step over the iterables in sequence without accessing the other members, zip or zip_longest() is the correct option. or, you could even do enumerate(zip(list1, list2)) and do both. And if you need your code to error when your iterables are not the same length, you should consider explicitly checking the lengths before entering the loop in the first place.
@shaheryarsohail9675
@shaheryarsohail9675 2 года назад
@@nigh_anxiety By definition, iterators are objects that contain contents of a list in an iterable manner. So that doesn't sit.
@monochromeart7311
@monochromeart7311 2 года назад
@@shaheryarsohail9675 that's fine, because zip is a generator. It holds references to the iterables passed to it and every call to "next()" (done automatically by the "for" loop) yields the next value.
@shaheryarsohail9675
@shaheryarsohail9675 2 года назад
@@monochromeart7311 It's still extra memory.
@anasjelloul4994
@anasjelloul4994 Год назад
which extension do you use for live execution python code?
@iamvalenci4
@iamvalenci4 2 года назад
I use that to build a dictinary with my lists
@dhaneshabhipraya
@dhaneshabhipraya 2 года назад
In this example I would use enumerate
@Taser12
@Taser12 10 месяцев назад
what is the theme you are using
@bittu007ize
@bittu007ize 2 года назад
Awesome
@lucasaschenbach
@lucasaschenbach 2 года назад
Which theme are you using?
@teablack8381
@teablack8381 2 года назад
I like how the accent makes the video convincible.
@suryac850
@suryac850 Год назад
Don't do this while building an application. Zipping is an extra operation that increases the tribe complexity of your code.
@bufdud4
@bufdud4 2 года назад
I've been using min this whole time.
@masterflitzer
@masterflitzer 2 года назад
yeah me too, is zip superior in any way? min seems much more logical too me
@michaelthornes
@michaelthornes 2 года назад
@@masterflitzer sounds like there's a parameter to throw an error in the case that the lists aren't equal, plus it's a bit simpler. I also heard it allocates more memory so just keep on using min
@solidzack
@solidzack Год назад
I'd say zip is better to read (though I just recently got into python. If you use for example: for i, (val1,val2) in enumerate(zip(a,b)): You also get the current index, but don't need to access the items of a and b manually with a[i] and b[i] each time. You could also rename val1 and val2 into more meaningful attribute names to make the loop even more understandable
@aaronaaron5013
@aaronaaron5013 2 года назад
When you do so much programming that your voice goes Indian
@keifer7813
@keifer7813 2 года назад
🤣
@adamharb9233
@adamharb9233 Год назад
😂😂😂😂😂
@Luvxaurora
@Luvxaurora Год назад
Nice
@sunnydeopa5
@sunnydeopa5 2 года назад
I would rather have an error than have the loop terminate at the shorter index without knowing.
@yamspaine
@yamspaine Год назад
... which gives you an error without an error message.
@eritert
@eritert 2 года назад
Didn’t even know you could loop multiple lists
@keifer7813
@keifer7813 2 года назад
I knew you could zip them together but the first method, I haven't seen. So simple yet not so obvious lol
@AnEnemyAnemone1
@AnEnemyAnemone1 Год назад
Wdym? In the first case, you’re just iterating over a range of integers, and accessing the corresponding indices. In the second case, you’re iterating over a single object that merges the two lists.
@AnEnemyAnemone1
@AnEnemyAnemone1 Год назад
@@keifer7813 You knew about zip before you knew about iterating over a range of integers and accessing elements by index? How does that happen lmao
@r.v.yuvaraj
@r.v.yuvaraj 2 года назад
Super
@greenscarf5417
@greenscarf5417 Год назад
use enumerate() for getting index, a more elegant function... for a more civilized age. for i, (l, r) in enumerate(zip(a,b))
@wharlheynunes6188
@wharlheynunes6188 9 месяцев назад
Nice algorithm 😊
@johnmorrell3187
@johnmorrell3187 2 года назад
I don't know if I love this solution, I'd usually rather have an error thrown if I expected both lists to be the same length and they aren't.
@eeriemyxi
@eeriemyxi 2 года назад
they added the `strict` keyword argument in python 3.10 which raises the desired error. It's not hard to implement this function in lower python versions that raises error when the other iterators still have values to yield and some don't.
@ilbutti6796
@ilbutti6796 2 года назад
damn, i come from c++ and this seems butter 🤤
@sachindubey7560
@sachindubey7560 2 года назад
So is it not an error 'Cause in case of " zip" we r getting 3rd value instead of 2
@mertgoksel744
@mertgoksel744 2 года назад
Yeah how do i change values if i dont get index?
@mikemcculley
@mikemcculley 2 года назад
Unless something makes at least an order of magnitude’s difference, I don’t understand why anyone would quibble about efficiency in Python. Python’s value is in its crisp syntax, and using zip here is cleaner IMO.
@yellowrose0910
@yellowrose0910 Год назад
Is Python just a bag of trick routines tagged onto BASIC? ("But the SPACES!:" they say...)
@adimetrius
@adimetrius 7 месяцев назад
This only pushes error detection (that lists are of different size, unlike expected) to i-dont-know-when. Or is it i-dont-care-when?
@shubham8550
@shubham8550 Год назад
just use one list and use this to get indexing for index,value in enumerate(urlist): print.....
@timerertim
@timerertim 2 года назад
German accent on point
@axumitedessalegn3549
@axumitedessalegn3549 Год назад
Lol I have a feeling the zip function just compares both lists and returns the shortest list range then runs it
@solidzack
@solidzack Год назад
Zip creates a new list of tuples (a, b)
@axumitedessalegn3549
@axumitedessalegn3549 Год назад
@@solidzack ohhh. Thanks! Did not know. Sorry only been coding for about 6 months. Just literally finished cs50.
@solidzack
@solidzack Год назад
@@axumitedessalegn3549 no problem i started learning Python about 4 month ago because of machine learning
@TheJAM_Sr
@TheJAM_Sr Год назад
In that example why not use enumerate?
@randyogue2032
@randyogue2032 Год назад
d = dict(zip(list1, list2)
@aycc-nbh7289
@aycc-nbh7289 2 года назад
So how will this work in non-Python languages?
@Redyf
@Redyf 2 года назад
What's the name of the theme youre ysing in vs code?
@patloeber
@patloeber 2 года назад
Tokyo Night Storm
@defacube
@defacube 2 года назад
And it looks way simpler.
@nczioox1116
@nczioox1116 Год назад
What about enumerate?
@vinnygz2540
@vinnygz2540 6 месяцев назад
Can you do it for three loops??
@korbiniankoch
@korbiniankoch 2 года назад
Not really sure if a silent failure is a feature here ...
@cristianoo2
@cristianoo2 2 года назад
Yep, silent failures are the worse nightmare in computer science, unfortunately people think this is "robust" lol
@mrboat3749
@mrboat3749 Год назад
What idle is this pla reply
@muddi900
@muddi900 2 года назад
Zip does not work at unequal length
@lukaschumchal7797
@lukaschumchal7797 2 года назад
I am little confused. Because of the video title I am not really sure what to do.
@chrism6880
@chrism6880 2 года назад
Don't use range(len)) at all... print(*list(zip(x,y)),sep=' ')
Далее
5 Good Python Habits
17:35
Просмотров 401 тыс.
While loops in Python are easy ♾️
6:58
Просмотров 318 тыс.
for Loop with Lists in Python
8:35
Просмотров 15 тыс.
If __name__ == "__main__" for Python Developers
8:47
Просмотров 383 тыс.
The purest coding style, where bugs are near impossible
10:25
how Google writes gorgeous C++
7:40
Просмотров 799 тыс.
Unlocking your CPU cores in Python (multiprocessing)
12:16
5 Useful F-String Tricks In Python
10:02
Просмотров 269 тыс.