0

Let's say I get a list, and I want to iterate on three at a time. I.e.: I have a list with [1,4,5,6,7,8,-9,2,0] In TCL, I can just use (for example):

foreach { x y z } $list {
   puts "x is ${x}"
   puts "y is ${y}"
   puts "z is ${z}"
}

How can I define more than 1 variable, using the for loop with the in (array name) in Python 3.3? The Python org wiki showed just example of 1 iteration variable. This is also easily done in Ruby
Thanks.

EDIT: The expected output is:

x is 1
y is 4
z is 5
x is 6
y is 7
z is 8
x is -9
y is 2
z is 0
SomethingSomething
  • 11,491
  • 17
  • 68
  • 126
user1134991
  • 3,003
  • 2
  • 25
  • 35
  • Can you tell what is the expected output of your sample program? What happens if the array length cannot be divided by 3? – SomethingSomething Apr 03 '18 at 09:34
  • I think this thread could help you, if this is your scenario. Hard to tell without the expected output for your example: https://stackoverflow.com/questions/5764782/iterate-through-pairs-of-items-in-a-python-list – SomethingSomething Apr 03 '18 at 09:37
  • You got it right. The assumption is that it is already qualified for the range of 3. It was a general syntax question. Thanks. – user1134991 Apr 03 '18 at 09:40
  • I'm still not sure whether you expect to see `1, 4, 5`, then `6, 7, 8` and then `-9, 2, 0`, OR whether you expect to see `1, 4, 5`, then `4, 5, 6`, then `5, 6, 7` and so on.. I think you should refine your question in order to be able to get a well-explained answer – SomethingSomething Apr 03 '18 at 09:42

1 Answers1

2

You can split this array into chunks, and then just do something like this:

for x,y,z in chunked_array:
    print("x=", x)
    print("y=", y)
    print("z=", z)
Nestor Yanchuk
  • 1,186
  • 8
  • 10