numeri1 = range(1,10) numeri2 = range(1,10,4) for elemento_1, elemento_2 in zip(numeri1, numeri2): print (elemento_1, elemento_2)
Quote:1 1
2 5
3 9
https://docs.python.org/3/library/functions.html#zip
If the sequences haven't the same length, the shortest win.
- numeri1 has 9 elements
- numeri2 has 3 elements
The function
itertools.zip_longest
will use by default None
as fillvalue.https://docs.python.org/3/library/iterto...ip_longest
from itertools import zip_longest numeri1 = range(1,10) numeri2 = range(1,10,4) for elemento_1, elemento_2 in zip_longest(numeri1, numeri2): print (elemento_1, elemento_2)
Quote:1 1
2 5
3 9
4 None
5 None
6 None
7 None
8 None
9 None
I think it's not what you want. Should
1 5 9
repeat the whole time?If it's the case:
from itertools import cycle numeri1 = range(1,10) numeri2 = cycle(range(1,10,4)) for elemento_1, elemento_2 in zip(numeri1, numeri2): print (elemento_1, elemento_2)Now numeri1 has still 9 elements (1..9) and numeri2 if infinite.
If you've an infinite generator/iterator, then better not use zip_longest (it will never finish).
Just use zip and the length of numeri1 defines the complete length.
The
itertools.cycle
function takes an Iterable (e.g. list or tuple) and cycle through them, until the end has been reached and then it starts from beginning.Or if you want to count until the first list is done:
https://docs.python.org/3/library/iterto...ools.count
from itertools import count numeri1 = range(1,10) numeri2 = count(1, 2) # <- this is infinite, so I don't have to think about length for elemento_1, elemento_2 in zip(numeri1, numeri2): print (elemento_1, elemento_2)
Quote:1 1
2 3
3 5
4 7
5 9
6 11
7 13
8 15
9 17
Itertools is powerful.
In addition, you can see, that it's straightforward to exchange parts of the program without changing much of the rest.
You need the zip function at many places.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!