how to iterate over several lists?
Minesh Patel
minesh at gmail.com
Fri Jun 5 14:37:49 EDT 2009
On Fri, Jun 5, 2009 at 10:20 AM, Tom<sevenbark at gmail.com> wrote:
> On Fri, 5 Jun 2009 04:07:19 +0000 (UTC), kj <no.email at please.post>
> wrote:
>
>>
>>
>>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
>
> def chain(*args):
> return (item for seq in args for item in seq)
>
> for x in chain(list_a, list_b):
> foo(x)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
If they are the same length, you can try the zip built-in function.
--
Thanks,
--Minesh
More information about the Python-list
mailing list