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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With