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
4
  • Can you tell what is the expected output of your sample program? What happens if the array length cannot be divided by 3? Commented Apr 3, 2018 at 9:34
  • I think this thread could help you, if this is your scenario. Hard to tell without the expected output for your example: stackoverflow.com/questions/5764782/… Commented Apr 3, 2018 at 9: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. Commented Apr 3, 2018 at 9: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 Commented Apr 3, 2018 at 9:42

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.