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.
@@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.
@@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
@@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.
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.
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
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.
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]
@@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.
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.
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
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.
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
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.
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?
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.
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.
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.
@@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
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
Find Python jobs: pythonengineer.pallet.com
Where are u doing this?
for i in range(min(len(a),len(b)))
Fuck that too many parenthesis
Thank you for this, much more efficient. I was gonna comment it but you beat me to it 😁
I think this is more readable.
@@ymaneboubleh3798 Flutter? fuck off of that, i hate it so much
# More readable
safeRange = min(len(a),len(b))
for index in range(safeRange):
There is also itertools.zip_longest() to fill-in missing values in uneven iterables
thanks
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 🥲
I like these videos. I always ignore the suggestions in the video and go to the comments for the correct/better solution.
savage but valid
This is a rare case where the video solution is actually the best
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.
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.
Also zip has an arguemnt where it can throw an error if the amount of elements is not equal.
Which makes it work just like the first option which zip was supposed to "replace". So, not a good tip after all
@@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.
@@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
@@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.
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
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])
Sometimes an error safes a lot of time searching for the reason of strange results 🤪
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.
Really liked the idea of quick learning tips videos like this. Big thumbs up.
While useful, often there is some sort of error if two lists which should be accessed in pairs have differing lengths.
You don't want it to stop at the shortest sequence, you want it to raise an exception.
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
Dude that's rly helpful for beginners! I appreciate your job!
This is awesome, you got yourself a new subscriber.
Enumerate >> zip
for idx, val in enumerate(b):
print(f’{idx} {val}’)
Now you can set "strict=True" in zip() to enforce same length criteria.
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:
That'd give you the cross product, which we don't want here. We want to access the items in pairs
a = [1,2,3]
b = ['one','two','three']
for i in range (0,3):
print (a[i], b[i])
you can also:
for index, value in zip(range(len(iter)), iter): ...
simpler
for i, numbers in enumerate(b, 1):
print(f”{i}: {numbers}”)
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.
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]
you can use enumerate for that
@@vns1956 zip uses more memory so it's worth just using indices
@@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.
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.
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
thank you so much, i was looking for this
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.
It's still true with C language,
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
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?
thank you big help! looking for this in a long time
Didn’t know it stops for the shortest sequence. Nice.
you can also use enumerate()
The first way failed with a traceable error, the second failed silently?
Which theme u use?
Those short tips are great! 🙏
Can you say name of your vscode theme?
How do i make an input and check if the input is in the list and if yes then check where in the list
I love theses videos I watch them for fun and knowledge 🤩
Didn't know that. Thanks🙌
Which theme are you using?
u r my fav python teacher
which extension do you use for live execution python code?
Nice tip
what is the theme you are using
You can also use enumarate
i needed this
In that example why not use enumerate?
Just so you know, the audio seems pretty loud in my headphones. You might need to mix it down a little bit!
So is it not an error
'Cause in case of " zip" we r getting 3rd value instead of 2
looked for this the whole day lmao
Yeah how do i change values if i dont get index?
use enumerate() for getting index, a more elegant function... for a more civilized age.
for i, (l, r) in enumerate(zip(a,b))
this is what I've been looking forrrr
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.
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?
Nice little tip 😁
For the next video please complete the topic lists in tuple
So how will this work in non-Python languages?
You absolutely amazing I love your clips
thank you
this is awesome 😎👍
just use one list and use this to get indexing
for index,value in enumerate(urlist):
print.....
What's wrong with using a min function?
I am little confused. Because of the video title I am not really sure what to do.
Thank you sir
I use that to build a dictinary with my lists
Funny you bring that up. So proud of my janky python hahaha
Great content
Really helpful 😍😍💕💕❤️
What's the name of the theme youre ysing in vs code?
Tokyo Night Storm
What about enumerate?
I like how the accent makes the video convincible.
Didn’t even know you could loop multiple lists
I knew you could zip them together but the first method, I haven't seen. So simple yet not so obvious lol
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.
@@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
Not really sure if a silent failure is a feature here ...
Yep, silent failures are the worse nightmare in computer science, unfortunately people think this is "robust" lol
What if I want to print the index of an element in a list of lists?
You can enumerate on the lists.
for lst in lst_of_lst:
for idx, element in enumerate(lst):
print(idx, element)
you can do smth like this:
for idx, (val1, val2) in enumerate(zip(lst1, lst2)):
...
for i in range(min(len(a),len(b)))
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.
Zip does not work at unequal length
In this example I would use enumerate
Don't do this while building an application. Zipping is an extra operation that increases the tribe complexity of your code.
thank's bro
What zip even means in this case? I don't think it's semantic code at all
Don't use range(len)) at all...
print(*list(zip(x,y)),sep='
')
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.
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.
Can you do it for three loops??
For i in Range(500)
(I only use Python for Turtle Module :))
Just loop through the min of the two lists, zip involves a lot of unnecessary operations.
... which gives you an error without an error message.
Zip ?
When you do so much programming that your voice goes Indian
🤣
😂😂😂😂😂
I would rather have an error than have the loop terminate at the shorter index without knowing.
Thx!
thanks
Lol I have a feeling the zip function just compares both lists and returns the shortest list range then runs it
Zip creates a new list of tuples (a, b)
@@solidzack ohhh. Thanks! Did not know. Sorry only been coding for about 6 months. Just literally finished cs50.
@@axumitedessalegn3549 no problem i started learning Python about 4 month ago because of machine learning
I've been using min this whole time.
yeah me too, is zip superior in any way? min seems much more logical too me
@@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
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
Ah... RIP izip
What idle is this pla reply
Is Python just a bag of trick routines tagged onto BASIC? ("But the SPACES!:" they say...)
Thankss!
d = dict(zip(list1, list2)
Why don't you use enumerate
Hello Sir, what kind of app are you using?
Nice algorithm 😊