how to iterate over several lists?

K

kj

Suppose I have two lists, list_a and list_b, and I want to iterate
over both as if they were a single list. E.g. I could write:

for x in list_a:
foo(x)
for x in list_b:
foo(x)

But is there a less cumbersome way to achieve this? I'm thinking
of something in the same vein as Perl's:

for $x in (@list_a, @list_b) {
foo($x);
}

TIA!

kynn

--
 
C

Chris Rebert

Suppose I have two lists, list_a and list_b, and I want to iterate
over both as if they were a single list.  E.g. I could write:

for x in list_a:
   foo(x)
for x in list_b:
   foo(x)

But is there a less cumbersome way to achieve this?  I'm thinking
of something in the same vein as Perl's:

for $x in (@list_a, @list_b) {
 foo($x);
}

Just add the lists together.

for x in list_a + list_b:
foo(x)

Cheers,
Chris
 
S

Stefan Behnel

kj said:
Suppose I have two lists, list_a and list_b, and I want to iterate
over both as if they were a single list. E.g. I could write:

for x in list_a:
foo(x)
for x in list_b:
foo(x)

But is there a less cumbersome way to achieve this?

Take a look at the itertools module, especially itertools.chain().

Stefan
 
M

Minesh Patel

def chain(*args):
 return (item for seq in args for item in seq)

for x in chain(list_a, list_b):
   foo(x)

If they are the same length, you can try the zip built-in function.
 
S

Steven D'Aprano

If they are the same length, you can try the zip built-in function.

Which does something *completely different* from what the Original Poster
was asking for.

Given alist = [1, 2, 3], blist = [4, 5, 6], the OP wants to process:

1, 2, 3, 4, 5, 6

but zip will give:

(1, 3), (2, 5), (3, 6)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top