I'm trying to iterate over X
s and y
s simultaneously unpacking them and using the enumerate()
function to count the pairs, as shown the following code:
X = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
Y = [[11, 21, 31, 41], [51, 61, 71, 81], [91, 101, 111, 121], [131, 141, 151, 161], [171, 181, 191, 201]]
index = 0
for x, y in zip(X, Y):
print(f'{index }, {x}, {y}')
index += 1
I'd like to save the index += 1
line, and be able to get all index, x and y in the for loop
What I've Tried:
enumerate
function on the zip
, but it requires me to unpack the x
and y
manually latter, as shown in the following code, and I'd like to save this line:X = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
Y = [[11, 21, 31, 41], [51, 61, 71, 81], [91, 101, 111, 121], [131, 141, 151, 161], [171, 181, 191, 201]]
for index, data in enumerate(zip(X, Y)):
x, y = data
print(f'{index}, {x}, {y}')
Desired Outcome:
The desired outcome may be seen in the following schematic pseudo-code:
#for index, x, y in zip(X, Y):
# print(f'{index }, {x}, {y}')
What am I missing here?
Thanks in advance.
you can unpack the value returned by enumerate
straight into the tuple (your pseudo-code just misses the brackets):
for index, (x, y) in enumerate(zip(X, Y)):
print(f'{index}, {x}, {y}')
-->
0, [1, 2, 3, 4], [11, 21, 31, 41]
1, [5, 6, 7, 8], [51, 61, 71, 81]
...