1

Let's say I have 2 lists

test1 = ["1","2","3"]
test2 = ["a","b","c","d","e"]

Now Id like to loop through both of them. But with the ability of test1 to repeat itself if the length of test2 is greater than test1

Ive found the zip function

for x , y in zip(test1,test2):
    print(x)
    print(y)

However this function will stop after all the elements of test1 have been iterated through

sample output

1
a
2
b
3
c

What id like to get is the following

1
a
2
b
3
c
1
d
2
e

thanks for the help!

3 Answers3

7

Use itertools.cycle() to keep repeating the first list.

import itertools

for x, y in zip(itertools.cycle(test1), test2):
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • To make this more generic for lists of unknown sizes, you could cycle both lists and use islice to limit the length to the max of the original lists. `islice(zip(cycle(test1), cycle(test2)), max(len(test1), len(test2))` – flakes Mar 29 '23 at 20:19
  • @flakes But I don't think they want to repeat `test2` if it's shorter. – Barmar Mar 29 '23 at 20:25
  • I very much doubt that in any real use case it's not known ahead of time which list is shorter. – chepner Mar 29 '23 at 20:31
  • Fair enough, just leaving it there for future readers who might have different requirements. – flakes Mar 29 '23 at 20:32
  • A common example is mapping values to colors in a plot, you need to repeat the colors if you run out. But you don't need to repeat values if you have more available colors. – Barmar Mar 29 '23 at 20:36
0

If it doesn´t have to include zip(), you could do something like this:

test1 = [1,2,3]
test2 = ["a","b","c","d","e"]
mi, ma = min(test1,test2,key=len),max(test1,test2,key=len) #sort the lists by lenght
for i,x in enumerate(ma):
    print(x,mi[i % len(mi)])

this will divide the index of an item in the longest list with the lenght of the shortest list and get the item at the index of the modulo in the shortest list.

River
  • 47
  • 7
  • I suspect `mi, ma = min(test1,test2,key=len),max(test1,test2,key=len) #sort the lists by lenght` will fail if the lists happen to be of the same size (both `mi` and `ma` will refer to the same list) – juanpa.arrivillaga Mar 29 '23 at 21:15
  • I suppose so, but if they are both the same lenght, using `zip()` would work just fine. – River Mar 30 '23 at 18:29
0

You can use the modulo operator (%) to calculate the index for list 1:

test1 = ["1","2","3"]
test2 = ["a","b","c","d","e"]

for index, item in enumerate(test2):
  # Print the item from list 1.
  index_of_test1 = (index % len(test1))
  print(test1[index_of_test1])

  # Print the item from list 2.
  print(item)

rdieleman
  • 64
  • 4