Reputation: 13
I'm trying to print every first num from each list in one line, I wasted like 1 hour on it trying but didn't the solution
Xx = [1298, 1390, 1487, 1573, 1669, 1766, 1766, 1672, 1573, 1485, 1392, 1297, 1303, 1388, 1487, 1577, 1664, 1757, 1763, 1671,
1577, 1487, 1393, 1298, 1301, 1376, 1449, 1535, 1604, 1682, 1760, 1769, 1676, 1568, 1485, 1398, 1300]
Yx = [331, 328, 328, 326, 329, 329, 422, 422, 416, 422, 419, 421, 514, 518, 516, 518, 518, 517, 605, 606, 605,
603, 602, 605, 730, 737, 736, 738, 740, 740, 742, 858, 869, 860, 857, 863, 864]
for posX, posY in (Xx, Yx):
print(posX, posY)
Error: for posX, posY in (Xx, Yx): ValueError: too many values to unpack (expected 2)
Upvotes: 1
Views: 41
Reputation: 7673
For iterating simultaneously in multiple list, you need zip()
.
zip
gives a tuple
containing the iterators of all the lists given as parameters to it.
Example: 1
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
for l, m, n in zip(l1, l2, l3):
print(l, m, n)
Output:
1 4 7
2 5 8
3 6 9
Example: 2
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9, 10]
l4 = [11, 12]
for l, m, n, o in zip(l1, l2, l3, l4):
print(l, m, n, o)
Output:
1 4 7 11
2 5 8 12
Note: that in Example:2 lists l3
and l4
had an unequal number of elements. So, zip
iterations are done only till the least number of elements of all the parameters li
Upvotes: 0
Reputation: 1515
If you intended to print numbers having same index from each list in the row together in one line and so on (going by your attempted code), you need to use zip:
for x, y in zip(Xx, Yx):
print(x, y)
If you intended to print only the first item of each list (you mentioned something like that)
print(Xx[0], Yx[0])
Upvotes: 1