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

Поделиться
HTML-код
  • Опубликовано: 22 дек 2024

Комментарии • 235

  • @patloeber
    @patloeber  2 года назад +4

    Find Python jobs: pythonengineer.pallet.com

  • @ArmirMitrandir
    @ArmirMitrandir 2 года назад +736

    for i in range(min(len(a),len(b)))

    • @vinpepper1384
      @vinpepper1384 2 года назад +146

      Fuck that too many parenthesis

    • @Alec9821
      @Alec9821 2 года назад +14

      Thank you for this, much more efficient. I was gonna comment it but you beat me to it 😁

    • @marcelocosta9620
      @marcelocosta9620 2 года назад +8

      I think this is more readable.

    • @simonchong7514
      @simonchong7514 2 года назад

      @@ymaneboubleh3798 Flutter? fuck off of that, i hate it so much

    • @neoesm
      @neoesm 2 года назад +25

      # More readable
      safeRange = min(len(a),len(b))
      for index in range(safeRange):

  • @davidc.890
    @davidc.890 2 года назад +193

    There is also itertools.zip_longest() to fill-in missing values in uneven iterables

    • @almajulio5842
      @almajulio5842 2 года назад

      thanks

    • @ziga1122
      @ziga1122 2 года назад +4

      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 года назад +234

    I like these videos. I always ignore the suggestions in the video and go to the comments for the correct/better solution.

    • @mechtist
      @mechtist 2 года назад +5

      savage but valid

    • @schlopping
      @schlopping 2 года назад +7

      This is a rare case where the video solution is actually the best

  • @eadweard.
    @eadweard. 2 года назад +20

    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 2 года назад +1

      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.

  • @higheloguy9057
    @higheloguy9057 2 года назад +87

    Also zip has an arguemnt where it can throw an error if the amount of elements is not equal.

    • @cristianoo2
      @cristianoo2 2 года назад +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 года назад +19

      @@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 года назад +11

      @@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.

  • @hn1f
    @hn1f 2 года назад +2

    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 Год назад

      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])

  • @patrick4406
    @patrick4406 2 года назад +75

    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.

  • @mohammadkeifary2009
    @mohammadkeifary2009 2 года назад +2

    Really liked the idea of quick learning tips videos like this. Big thumbs up.

  • @AnyVideo999
    @AnyVideo999 2 года назад +8

    While useful, often there is some sort of error if two lists which should be accessed in pairs have differing lengths.

  • @guidosalescalvano9862
    @guidosalescalvano9862 2 года назад +2

    You don't want it to stop at the shortest sequence, you want it to raise an exception.

  • @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

  • @Roman-rs6um
    @Roman-rs6um Год назад

    Dude that's rly helpful for beginners! I appreciate your job!

  • @taloki8738
    @taloki8738 2 года назад +1

    This is awesome, you got yourself a new subscriber.

  • @jacobharmon6162
    @jacobharmon6162 2 года назад

    Enumerate >> zip
    for idx, val in enumerate(b):
    print(f’{idx} {val}’)

  • @AshishRanjan-jn7re
    @AshishRanjan-jn7re 2 года назад +1

    Now you can set "strict=True" in zip() to enforce same length criteria.

  • @David-IoanStanescu47
    @David-IoanStanescu47 2 года назад

    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 2 года назад

      That'd give you the cross product, which we don't want here. We want to access the items in pairs

  • @xpita0_041
    @xpita0_041 2 года назад

    a = [1,2,3]
    b = ['one','two','three']
    for i in range (0,3):
    print (a[i], b[i])

  • @aaskrad
    @aaskrad 2 года назад

    you can also:
    for index, value in zip(range(len(iter)), iter): ...

  • @gonzalotoloza6700
    @gonzalotoloza6700 Год назад

    simpler
    for i, numbers in enumerate(b, 1):
    print(f”{i}: {numbers}”)

  • @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.

  • @eternablue730
    @eternablue730 2 года назад +11

    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 года назад +1

      you can use enumerate for that

    • @michaelthornes
      @michaelthornes 2 года назад +1

      @@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.

  • @christopherdyson1158
    @christopherdyson1158 2 года назад

    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.

  • @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

  • @mahdi-hasan
    @mahdi-hasan 2 года назад +1

    thank you so much, i was looking for this

  • @ytechnology
    @ytechnology 2 года назад +1

    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.

  • @solidzack
    @solidzack 2 года назад

    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

  • @adimetrius
    @adimetrius Год назад

    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?

  • @junyooor7582
    @junyooor7582 2 года назад

    thank you big help! looking for this in a long time

  • @phipag1997
    @phipag1997 2 года назад +2

    Didn’t know it stops for the shortest sequence. Nice.

  • @lorenzobarone45
    @lorenzobarone45 2 года назад +9

    you can also use enumerate()

  • @MoneyMitch-AceDuece
    @MoneyMitch-AceDuece 2 года назад +1

    The first way failed with a traceable error, the second failed silently?

  • @parampatel8853
    @parampatel8853 2 года назад +1

    Which theme u use?

  • @Tennisbull-match-statistics
    @Tennisbull-match-statistics 2 года назад +4

    Those short tips are great! 🙏

  • @collapser_team
    @collapser_team 2 года назад +2

    Can you say name of your vscode theme?

  • @Idontlikebeingsad
    @Idontlikebeingsad 4 месяца назад

    How do i make an input and check if the input is in the list and if yes then check where in the list

  • @sarahjamal86
    @sarahjamal86 2 года назад +1

    I love theses videos I watch them for fun and knowledge 🤩

  • @sankalpmane9029
    @sankalpmane9029 2 года назад

    Didn't know that. Thanks🙌

  • @lucasaschenbach
    @lucasaschenbach 2 года назад

    Which theme are you using?

  • @Sameer-rd5fm
    @Sameer-rd5fm 2 года назад

    u r my fav python teacher

  • @anasjelloul4994
    @anasjelloul4994 Год назад

    which extension do you use for live execution python code?

  • @hadawardgz
    @hadawardgz 2 года назад +1

    Nice tip

  • @Taser12
    @Taser12 Год назад

    what is the theme you are using

  • @SupreemeSteevee
    @SupreemeSteevee 8 месяцев назад

    You can also use enumarate

  • @drkings2055
    @drkings2055 2 года назад

    i needed this

  • @TheJAM_Sr
    @TheJAM_Sr 2 года назад

    In that example why not use enumerate?

  • @loganclark3642
    @loganclark3642 2 года назад +14

    Just so you know, the audio seems pretty loud in my headphones. You might need to mix it down a little bit!

  • @sachindubey7560
    @sachindubey7560 2 года назад

    So is it not an error
    'Cause in case of " zip" we r getting 3rd value instead of 2

  • @kastannie9045
    @kastannie9045 Год назад

    looked for this the whole day lmao

  • @mertgoksel35
    @mertgoksel35 2 года назад

    Yeah how do i change values if i dont get index?

  • @greenscarf5417
    @greenscarf5417 2 года назад

    use enumerate() for getting index, a more elegant function... for a more civilized age.
    for i, (l, r) in enumerate(zip(a,b))

  • @axospyeyes281
    @axospyeyes281 2 года назад

    this is what I've been looking forrrr

  • @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.

  • @arekxv
    @arekxv 2 года назад +1

    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?

  • @USELESSFACTSDAILYDAY
    @USELESSFACTSDAILYDAY 2 года назад

    Nice little tip 😁

  • @rohitghosh475
    @rohitghosh475 2 года назад

    For the next video please complete the topic lists in tuple

  • @aycc-nbh7289
    @aycc-nbh7289 2 года назад

    So how will this work in non-Python languages?

  • @newsjuice7404
    @newsjuice7404 2 года назад

    You absolutely amazing I love your clips

  • @juriwerth
    @juriwerth 2 года назад +1

    thank you

  • @InTranceofficial
    @InTranceofficial 2 года назад

    this is awesome 😎👍

  • @shubham8550
    @shubham8550 2 года назад

    just use one list and use this to get indexing
    for index,value in enumerate(urlist):
    print.....

  • @charlemagnejavinal2926
    @charlemagnejavinal2926 2 года назад

    What's wrong with using a min function?

  • @lukaschumchal7797
    @lukaschumchal7797 2 года назад

    I am little confused. Because of the video title I am not really sure what to do.

  • @yan2410
    @yan2410 2 года назад

    Thank you sir

  • @iamvalenci4
    @iamvalenci4 2 года назад

    I use that to build a dictinary with my lists

  • @nonono6400
    @nonono6400 2 года назад +1

    Funny you bring that up. So proud of my janky python hahaha

  • @gavincoulson3900
    @gavincoulson3900 2 года назад

    Great content

  • @its_code
    @its_code 2 года назад

    Really helpful 😍😍💕💕❤️

  • @Redyf
    @Redyf 2 года назад

    What's the name of the theme youre ysing in vs code?

  • @rafaelfreitastrad9746
    @rafaelfreitastrad9746 2 года назад

    What about enumerate?

  • @teablack8381
    @teablack8381 2 года назад

    I like how the accent makes the video convincible.

  • @eritert
    @eritert 2 года назад +1

    Didn’t even know you could loop multiple lists

    • @keifer7813
      @keifer7813 2 года назад +1

      I knew you could zip them together but the first method, I haven't seen. So simple yet not so obvious lol

    • @AnEnemyAnemone1
      @AnEnemyAnemone1 2 года назад

      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 2 года назад

      @@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

  • @korbiniankoch
    @korbiniankoch 2 года назад +1

    Not really sure if a silent failure is a feature here ...

    • @cristianoo2
      @cristianoo2 2 года назад +1

      Yep, silent failures are the worse nightmare in computer science, unfortunately people think this is "robust" lol

  • @accyamasomo1365
    @accyamasomo1365 2 года назад

    What if I want to print the index of an element in a list of lists?

    • @GOTHICforLIFE1
      @GOTHICforLIFE1 2 года назад +1

      You can enumerate on the lists.
      for lst in lst_of_lst:
      for idx, element in enumerate(lst):
      print(idx, element)

    • @dp.229
      @dp.229 2 года назад +1

      you can do smth like this:
      for idx, (val1, val2) in enumerate(zip(lst1, lst2)):
      ...

    • @XekoN10
      @XekoN10 2 года назад

      for i in range(min(len(a),len(b)))

    • @cristianoo2
      @cristianoo2 2 года назад +1

      Just stick with the good old indexed for. Use this only if it's your intention, not as a substitution.
      If you need the index, use the index.
      A clean code approach should be to first verify the length of the two input arrays and then execute the for loop.
      Never mix two functionalities on the same code. If loop is supposed to receive two equal sized arrays, just test them first and make sure they fit the problem.
      This recommendation is actually bad coding.

  • @muddi900
    @muddi900 2 года назад

    Zip does not work at unequal length

  • @dhaneshabhipraya
    @dhaneshabhipraya 2 года назад

    In this example I would use enumerate

  • @suryac850
    @suryac850 2 года назад

    Don't do this while building an application. Zipping is an extra operation that increases the tribe complexity of your code.

  • @brandonallen2301
    @brandonallen2301 2 года назад +1

    thank's bro

  • @hil449
    @hil449 2 года назад

    What zip even means in this case? I don't think it's semantic code at all

  • @chrism6880
    @chrism6880 2 года назад

    Don't use range(len)) at all...
    print(*list(zip(x,y)),sep='
    ')

  • @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.

  • @vinnygz2540
    @vinnygz2540 Год назад

    Can you do it for three loops??

  • @leonbotschok4156
    @leonbotschok4156 2 года назад

    For i in Range(500)
    (I only use Python for Turtle Module :))

  • @parkershaw8529
    @parkershaw8529 2 года назад

    Just loop through the min of the two lists, zip involves a lot of unnecessary operations.

  • @yamspaine
    @yamspaine 2 года назад +1

    ... which gives you an error without an error message.

  • @nursyafaudin4962
    @nursyafaudin4962 2 года назад

    Zip ?

  • @aaronaaron5013
    @aaronaaron5013 2 года назад +1

    When you do so much programming that your voice goes Indian

  • @sunnydeopa5
    @sunnydeopa5 2 года назад

    I would rather have an error than have the loop terminate at the shorter index without knowing.

  • @No_Underscore
    @No_Underscore 2 года назад

    Thx!

  • @tankhaiinh1729
    @tankhaiinh1729 2 года назад +2

    thanks

  • @axumitedessalegn3549
    @axumitedessalegn3549 2 года назад

    Lol I have a feeling the zip function just compares both lists and returns the shortest list range then runs it

    • @solidzack
      @solidzack 2 года назад +1

      Zip creates a new list of tuples (a, b)

    • @axumitedessalegn3549
      @axumitedessalegn3549 2 года назад

      @@solidzack ohhh. Thanks! Did not know. Sorry only been coding for about 6 months. Just literally finished cs50.

    • @solidzack
      @solidzack 2 года назад

      @@axumitedessalegn3549 no problem i started learning Python about 4 month ago because of machine learning

  • @bufdud4
    @bufdud4 2 года назад +5

    I've been using min this whole time.

    • @masterflitzer
      @masterflitzer 2 года назад +1

      yeah me too, is zip superior in any way? min seems much more logical too me

    • @michaelthornes
      @michaelthornes 2 года назад +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 2 года назад

      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

  • @NoProblem76
    @NoProblem76 2 года назад +1

    Ah... RIP izip

  • @mrboat3749
    @mrboat3749 2 года назад

    What idle is this pla reply

  • @yellowrose0910
    @yellowrose0910 2 года назад

    Is Python just a bag of trick routines tagged onto BASIC? ("But the SPACES!:" they say...)

  • @juanpunch8473
    @juanpunch8473 2 года назад

    Thankss!

  • @randyogue2032
    @randyogue2032 Год назад

    d = dict(zip(list1, list2)

  • @bhanumedapalli2480
    @bhanumedapalli2480 Год назад

    Why don't you use enumerate

  • @carlosantos7163
    @carlosantos7163 2 года назад

    Hello Sir, what kind of app are you using?

  • @wharlheynunes6188
    @wharlheynunes6188 Год назад

    Nice algorithm 😊