How to iterate over x number of lists using zip

2.1k views Asked by At

I have several lists which I need to iterate over. I've got the zip function working very nicely, but to make my code more flexible I was wondering how you would use zip, but get the number of lists from a variable?

For example, rather than:

for 1,2,3 in zip(list_1,list_2,list3):
    do something

We can do something more like:

i = 1   
var = number of lists 
zipall = zip(all_my_lists)


for i in range(1,var) in zip(zipall):
    do something

This code isn't even close to working, I was just wanting to give an idea of the sort of thing I want to be able to do. Any tips would be very much appreciated. Thanks in advance.

Update

Thanks for the tips so far. It looks like using the * function might do the job for me. So far I'm trying the get the first half of my zip statement working:

args = [0,1]
for i in range(*args) in zip(outputlist[0],outputlist[1]):
    print range(*args)

but line beginning "for" is giving me the following error:

TypeError: 'bool' object is not iterable

Any idea where I am going wrong? Thanks very much for the help so far.

2

There are 2 answers

0
Inbar Rose On

First of all, the actual lists need to be specified, or be in another collection so that you can dynamically access them. Assuming you have a list of lists, you can easily do the following:

all_lists = [range(2),
             range(2),
             range(2)]

def zip_test(sentinal=1):
    for items in zip(*all_lists[:sentinal]):
        print items

# demonstration
>>> zip_test(1)
(0,)
(1,)
>>> zip_test(2)
(0, 0)
(1, 1)
>>> zip_test(3)
(0, 0, 0)
(1, 1, 1)
2
Alex Huszagh On

You might be interested in * and **: What does ** (double star) and * (star) do for parameters?

  • basically converts a list and translates all as arguments within a function call.

So:

myfunc(1,2,3)

Is the same as

myfunc(*[1,2,3])

This is pointless if you have a defined number of variables and a defined scope, but if you have a variable number of parameters, use the * arg to zip the list and iterate over all of them.

EDIT: You're doing a few things wrong now.

As it stands, this would fix your code, but I doubt this is your intent.

def myfunc(*args):    # this passes an arbitrary number of values
    length = len(args)
    # you cannot add a second "in:, this makes a comparison
    # like 5 > 4, or something, which returns a boolean value
    for i in range(0, length):
        do_something(i)       # this does something to the index

I believe this is your goal: to do something to all lists:

def myfunc(*args):
    for arg in args:       # grabs each list sequentially
        do_something(arg)