menu

Enumerate and zip

  • date_range 10/05/2022 10:34 info
    sort
    Python
    label
    loops

Enumerate and Zip are 2 powerful functions available in python when looping over lists.

I encountered this little problem when trying to run enumerate over a zip of multiple lists

a = [1,2,3,4]
b = [4,3,2,1]
for i,a,b in enumerate(zip(a,b)):
	print(i,a,b)
ValueError: not enough values to unpack (expected 3, got 2)

In order to overcome this, the values that needs to be unpacked from the zip function needs to be defined in parentheses

a = [1,2,3,4]
b = [4,3,2,1]
for i,(a,b) in enumerate(zip(a,b)):
	print(i,a,b)
0 1 4
1 2 3
2 3 2
3 4 1

The value can then also be unpacked as a tuple

a = [1,2,3,4]
b = [4,3,2,1]
for i,t in enumerate(zip(a,b)):
	print(i,t)
0 (1, 4)
1 (2, 3)
2 (3, 2)
3 (4, 1)
Buy me a coffeeBuy me a coffee