foodisgood
foodisgood

Reputation: 23

How do I make the same iteration for several different lists at the same time in Python

if i have multiple lists at different lengths is there a simple way to make the same iteration on all of them.

so insted of writing something like:

for item in list1:
    function(item)
for item in list2:
    function(item)
.
.
.
for item in listn:
   function(item)

i just write something like:

for item in list1,list2,...,listn:
    function(item)

I know you can do this by combining the lists by i want something more efficient than having to combine them each time i call the function

Upvotes: 2

Views: 60

Answers (2)

thefourtheye
thefourtheye

Reputation: 239553

You can create a generator expression, which would give items one by one from individual lists, like this

for item in (elem for c_list in (list1, list2, list3) for elem in c_list)):
    function(item)

For example,

>>> def function(item):
...     print item
... 
>>> list1, list2, list3 = [1, 2], [3, 4], [5, 6]
>>> for item in (elem for c_list in (list1, list2, list3) for elem in c_list):
...     function(item)
... 
1
2
3
4
5
6

Note: The generator expression which we create is not concatenating all the lists, but it just iterates the tuple of lists and then iterates the individual lists to get the elements one by one.

Upvotes: 2

glglgl
glglgl

Reputation: 91099

Tasks which have to do with iteration are covered by the itertools module.

There you have a chain() function which can do

import itertools
for item in itertools.chain(list1, list2, list3):
    function(item)

BTW, the whole standard lib documentation is worth reading, there are a lot of interesting things which can prevent you from re-inventing the wheel.

Upvotes: 11

Related Questions