Basically I have these 2 lists
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']
And I want to iterate over both of the lists synchronously and whenever the shortest list ends (listtwo in this case) is restarts again until listone is finished. Example:
a 1
b 2
c 3
d 1
e 2
f 3
j 1
Like this.
We can iterate over a single Python list using a for loop or a range() function. The range(start, stop, step) function enables us to get a sequence of numbers from a defined range of values.
You can use the zip() function to join lists together. The zip() function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments. Finally, just join() them together with newlines and you have the string you want.
To iterate through 2 or more different lists can be done using 2 functions, they are To use zip function we must import the itertools module. Importing this module is as same as any other module in python. Zip () function must be used when the user wants to stop printing after anyone of the lists completes iterating.
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step.
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).
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. If you have your lists in a list, itertools.chain.from_iterable is available: l = [l1, l2] for i in itertools.chain.from_iterable (l): print (i, end=" ") Which yields the same result.
you can use itertools.cycle:
from itertools import cycle
for i, j in zip(listone, cycle(listtwo)):
print(i, j)
output:
a 1
b 2
c 3
d 1
e 2
f 3
j 1
Without itertools.cycle()
or creating secondary list:
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']
N = len(listtwo)
for index, elem in enumerate(listone):
elem2 = listtwo[index % N]
print(elem, elem2)
from math import ceil
listone = ['a', 'b', 'c', 'd', 'e', 'f', 'j']
listtwo = ['1', '2', '3']
listtwo_augmented = listtwo * ceil(len(listone)/len(listtwo))
for e1, e2 in zip(listone, listtwo_augmented):
print(e1, e2)
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