Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - iterate through list whose elements have variable length

How can I iterate through a list or tuple whose elements as lists with variable length in Python? For example I want to do

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in tup:
     print a,b,c,d

and then have the elements of tup that are short to be completed with, say, None. I have found a workaround with the following code but I believe there must be a better way.

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in [ el if len(el)==4 else [ el[i] if i<len(el) else None for i in range(4)] for el in tup ]:
     print a,b,c,d

Where 4 is actually the length of the "longest" element.

Is there a better way?

like image 742
TomCho Avatar asked May 05 '15 18:05

TomCho


People also ask

How do you iterate the length of a list in Python?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

How do you iterate over a variable in Python?

You should just use a list. You'll then be able to iterate over the elements using a for loop. You will also be able to address the elements by index: x[i] . Bear in mind that list indices start from zero and not one.


1 Answers

To match your own output you can use izip_longest to fill with None's and transpose again to get back to the original order:

from itertools import izip_longest

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7] )
for a,b,c,d in zip(*izip_longest(*tup)):
    print(a,b,c,d)
(1, 2, None, None)
(2, 3, 5, None)
(4, 3, None, None)
(4, 5, 6, 7)

If an int, float etc.. would be better then you can specify a different fillvalue argument to the izip_longest function:

tup=( [1,2], [2,3,5], [4,3], [4,5,6,7])
for a,b,c,d in zip(*izip_longest(*tup,fillvalue=0)):
    print(a,b,c,d)

(1, 2, 0, 0)
(2, 3, 5, 0)
(4, 3, 0, 0)
(4, 5, 6, 7)

Judging by your print statement you are likely to be using python2 but for anyone using python3 as @TimHenigan commented below it is zip_longest.

If you don't need a list you can use itertools.izip which returns an iterator:

 from itertools import izip_longest, izip

tup = ( [1, 2], [2, 3, 5], [4, 3], [4, 5, 6, 7])
for a, b, c, d in izip(*izip_longest(*tup, fillvalue=0)):
    print(a, b, c, d)
like image 175
Padraic Cunningham Avatar answered Sep 21 '22 14:09

Padraic Cunningham