Reputation: 691
Given the following lists:
letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
numbers = ('1', '2', '3', '4')
How can I produce an iterated list that produces the following:
output = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'),
('e', '1'), ('f', '2'), ('g', '3'), ('a', '4'),
('b', '1'), ('c', '2'), ('d', '3'), ('e', '4'),
('f', '1'), ('g', '2')...]
I feel like I should be able to produce the desired output by using
output = (list(zip(letters, itertools.cycle(numbers))
But this produces the following:
output = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'),
('e', '1'), ('f', '2'), ('g', '3')]
Any help would be greatly appreciated.
Upvotes: 1
Views: 59
Reputation: 44009
If you want a finite list of elements, this should work
import itertools
letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g')
numbers = ('1', '2', '3', '4')
max_elems = 10
list(itertools.islice((zip(itertools.cycle(letters), itertools.cycle(numbers))), max_elems))
results in
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), ('e', '1'), ('f', '2'), ('g', '3'), ('a', '4'), ('b', '1'), ('c', '2')]
Upvotes: 0
Reputation: 16204
If you are looking for an infinite generator, you can use cycle
with zip
for both lists, in the form of zip(itertools.cycle(x), itertools.cycle(y))
. That would supply you with the required generator:
>>> for x in zip(itertools.cycle(letters), itertools.cycle(numbers)):
... print(x)
...
('a', '1')
('b', '2')
('c', '3')
('d', '4')
('e', '1')
('f', '2')
('g', '3')
('a', '4')
('b', '1')
('c', '2')
('d', '3')
...
Upvotes: 1