0

I think this might be very easy to do, but I don't know exactly how I can. Suppose that we have multiple arrays:

x = [1, 2, 3, 4, 5]
y = [1, 3, 5, 7 ,9]
z = [1, 5, 10, 15, 20]

Then, how can I get each element of each array using the for loop? What I'm trying to do is something like the following:

for (x1, x2, x3) in (x, y, z):
  print (x1, x2, x3)

Of course, the above code block doesn't work. Could anyone tell me how I can do this?

chanwcom
  • 4,420
  • 8
  • 37
  • 49

2 Answers2

1

Assuming x, y and z are always the same length, you can use the built-in zip() function:

x = [1, 2, 3, 4, 5]
y = [1, 3, 5, 7 ,9]
z = [1, 5, 10, 15, 20]

for (x1, x2, x3) in zip(x, y, z):
    print(x1, x2, x3)

Output

(1, 1, 1)
(2, 3, 5)
(3, 5, 10)
(4, 7, 15)
(5, 9, 20)

If x, y and z are not of the same length then zip() will return a list of tuples truncated in length to min(len(x), len(y), len(z)).

gtlambert
  • 11,711
  • 2
  • 30
  • 48
0

You can use the zip function that creates a list of tuples:

>>> zip(x,y,z)
[(1, 1, 1), (2, 3, 5), (3, 5, 10), (4, 7, 15), (5, 9, 20)]

Zip thus generates - for the given lists - a list of tuples such that tuple Ti consists out of the elements Xi, Yi and Zi.

Next you can iterate over these tuples:

for (x1, x2, x3) in zip(x, y, z):
  print (x1, x2, x3)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555