Germán
Germán

Reputation: 65

How do I iterate between lists of different lenghts?

I have two lists which I need to Iterate together. Let me show how:

listA=[1,2,3,4]
listB=["A","B","C"]

From those lists I would like to have this list

ListC=("1A","2B","3C","4A")

And even make a longer list in which I can loop the same iteration

ListC=("1A","2B","3C","4A","1B","2C","3A","4C".... and so on)

I couldn`t find any tutorial online that would answer this question Thanks.

Upvotes: 1

Views: 78

Answers (3)

chepner
chepner

Reputation: 530970

Use zip and itertools.cycle:

>>> from itertools import cycle
>>> listA = [1, 2, 3, 4]
>>> listB = ["A", "B", "C"]
>>> [f'{x}{y}' for x, y in zip(listA, cycle(listB))]
['1A', '2B', '3C', '4A']

# listA:         1    2    3    4
# cycle(listB): "A"  "B"  "C"  "A"  "B"  "C" ...

cycle endlessly cycles through the elements of its argument; zip stops iterating after its shorter argument is exhausted.

You can use cycle with both lists, but the result will be an infinite sequence of values; you'll need to use something like itertools.islice to take a finite prefix of the result.

>>> from itertools import cycle, islice
>>> [f'{x}{y}' for x, y in islice(zip(cycle(listA), cycle(listB)), 8)]
['1A', '2B', '3C', '4A', '1B', '2C', '3A', '4B']

# cycle(listA):  1   2   3   4   1   2   3   4   1   2   3   4   1  ...
# cycle(listB): "A" "B" "C" "A" "B" "C" "A" "B" "C" "A" "B" "C" "A" ...
# Note that the result itself is a cycle of 12 unique elements, because
# the least common multiple (LCM) of 3 and 4 is 12.

Upvotes: 8

Pikaxhuu
Pikaxhuu

Reputation: 1

listA=[1,2,3,4]
listB=["A","B","C"]
listC=[]

for a in listA:
    index = listA.index(a)
    if listA.index(a) > len(listB) - 1:
        if listC[-1][1] != listB[-1]:
            index = listB.index(listC[-1][1]) + 1
        else:
            index = 0
    listC.append(str(a)+listB[index])

print(listC)

Upvotes: 0

Ultimat0
Ultimat0

Reputation: 51

You can use modulo to take care of this kind of problem. Here's code to repeat this 100 times:

l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c']

result = []
for i in range(100):
    result.append(str(l1[i % len(l1)]) + l2[i % len(l2)])

print (result)

Upvotes: 1

Related Questions