In my Python 3 script, I am trying to make a combination of three numbers from three different lists based on inputs. If the lists are the same size, there is no issue with zip
. However, I want to be able to input a single number for a specific list and the script to repeat that number until the longest list is finished. This can be done with zip_longest
. However, with fillvalue
it is not possible to have separate fill values for separate lists.
Taking this simple script as an example:
from itertools import zip_longest
list1=[1]
list2=[4, 5, 6, 7, 8, 9]
list3=[2]
for l1, l2, l3 in zip_longest(list1, list2, list3):
print(l1, l2, l3)
This is the actual result:
# 1 4 2
# None 5 None
# None 6 None
# None 7 None
# None 8 None
# None 9 None
And this would be the result that I want:
# 1 4 2
# 1 5 2
# 1 6 2
# 1 7 2
# 1 8 2
# 1 9 2
I already managed to do this specific task by manually creating different for loops and asking if a list is a constant or not, but zip_longest
is so close to exactly what I need that I wonder if I am missing something obvious.
See the code below. If you need to iterate through two lists till the longest one ends, use itertools.zip_longest (). It works just like the zip () function except that it stops when the longest list ends. It fills the empty values with None, and returns an iterator of tuples.
For better understanding of iteration of multiple lists, we are iterating over 3 lists at a time. zip () : In Python 3, zip returns an iterator. zip () function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.
Best for… One of the simplest ways to loop over a list in Python is by using a for loop. A for loop allows you to iterate over an interable object (like a list) and perform a given action. This approach is intuitive because it loops over each item in the list (unless explicitly stopped).
Iterating using the index is not recommended if we can iterate over the elements (as done in Method #1). Method #4: Using list comprehension (Possibly the most concrete way).
You could make use of logical or
operator to use the last element of the shorter lists:
from itertools import zip_longest
list1 = [1]
list2 = ["a", "b", "c", "d", "e", "f"]
list3 = [2]
for l1, l2, l3 in zip_longest(list1, list2, list3):
print(l1 or list1[-1], l2, l3 or list3[-1])
Out:
1 a 2
1 b 2
1 c 2
1 d 2
1 e 2
1 f 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With