Good way to iterate lists of different lengths and set default value
Good way to iterate lists of different lengths and set default value
In Python, is there a good way to iterate through lists of different lengths?
For example,
a = [1,2,3]
b=[4,5]
c = [a,b]
for val1, val2, val3 in c:
print val1
print val2
print val3
Assuming that the list will have at least 2 values, and in some list, 3rd value is optional. The above for
loop didn't work for b, obviously, that val3 is not available for list 'b'. In that case, I want to print the val3 as 0. Can I give a default value in case of unavailability?
for
for val1, val2, val3=0 in c:
The above syntax didn't work either. Please help.
5 Answers
5
If you want to be fancy ("elegant"?), you can pad a given list with zeros:
def pad_list(t, size, default):
return t + [default] * (size - len(t))
for x in c:
v1, v2, v3 = pad_list(x, 3, 0)
print(v1)
print(v2)
print(v3)
Similarly, if you're working with tuples, here's another function:
def pad_list(t, size, default):
return t + (default,) * (size - len(t))
You could use zip_longest
with fillvalue
handling empty slot for this case:
zip_longest
fillvalue
from itertools import zip_longest
a = [1,2,3]
b = [4,5]
l =
for x, y in zip_longest(a, b, fillvalue=0):
l.append((x, y))
print(list(zip(*l)))
# [(1, 2, 3), (4, 5, 0)]
If you need values out of list, just replace last print
with:
print
for val1, val2, val3 in zip(*l):
print(val1)
print(val2)
print(val3)
# 1
# 2
# 3
# 4
# 5
# 0
zip(*zip_longest(*c, fillvalue=0))
c = [a, b]
c
this is very simple
c = [1,2,3]
val1 , val2 , *val3= [1,2 , 3]
val1 = 1 , val2 =3 , val3=[3]
c=[1,2]
val1 , val2 , *val3= [1,2 , 3]
val1 = 1 , val2 =3 , val3=
def foreach(l):
def deco(f):
for xs in l:
f(*xs)
return deco
@foreach([[1, 2, 3], [4, 5]])
def _(a, b, c=6):
print(a, b, c, sep='n')
The simplest method to concatenate the lists is via chain
function from the itertools
module.
chain
itertools
import itertools
a = [1, 2, 3, 4, 5, 6]
b = [7, 8, 9, 10, 11, 12]
c = ['A', 'B', 'C', 'D', 'E', 'F', 'U']
combined = itertools.chain( a, b, c ) # combines in order
# enumerate lists to allow for iteration
for index, value in enumerate(combined):
print(value, end = ' ')
1 2 3 4 5 6 7 8 9 10 11 12 A B C D E F U
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
More succinctly (and generally),
zip(*zip_longest(*c, fillvalue=0))
wherec = [a, b]
. This works with arbitrarily sizedc
.– Mateen Ulhaq
2 days ago