relgukxilef
relgukxilef

Reputation: 392

python iterator over multiple lists

I have a list of lists and want to get an iterator over every element in every list.

My idea is to write a class with two variables: The iterator over the lists and the iterate over the current inner list. Whenever the inner list iterator raises StopIteration I call next on the outer list iterator. My way of doing this contains a lot of nested ifs in the next function so I'm asking you what the pythonic way of doing this is.

Example:

lists = [[1, 2].__iter__(), [3, 4].__iter__()]

Now I need an iterator object that iterates over 1, 2, 3 and 4. Because the list's I'm working with are very big I can only use iterators.

Upvotes: 0

Views: 2332

Answers (2)

alexpinho98
alexpinho98

Reputation: 909

Use izip: izip(*nested) or just 'zip' if your on Python 3.x

The * operator is the argument unpacking operator and it allows a tuple or a list to be 'spread out' through statements. Another example of this is:

list = (1, 2, 3, 4, 5)

a, *bcd, e = list # a=1, bcd=[2,3,4] and e=5

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124948

Use itertools.chain.from_iterable():

from itertools import chain

for elem in chain.from_iterable(nested_list):

Demo:

>>> from itertools import chain
>>> nested_list = [['a', 'b'], ['c', 'd']]
>>> for elem in chain.from_iterable(nested_list):
...     print elem,
... 
a b c d

Upvotes: 4

Related Questions