4

I have 3 lists of equal sizes (List1,2 and 3). I want to iterate through the list and and perform operations on each of the items. Like

for x in List1, y in List2, z in List3:
    if(x == "X" or x =="x"):
         //Do operations on y
    elif(y=="Y" or y=="y"):
         //Do operations on x,z

So I want to traverse the list only for "Length of List1 or 2 or size" and then perform operations on x,y and z. How can I do this using Python?

Edit: Python Version 2.6.6

2 Answers 2

8
import itertools
for x, y, z in itertools.izip(List1, List2, List3):
    # ...

Or just zip in Python 3.

Sign up to request clarification or add additional context in comments.

3 Comments

@wim: It'd be good if you'd want to use the zipped list more than once. It's better to work with iterators/views if all you want is to iterate over it once.
but I am using Python 2.6.6 and itertools is not defined.
itertools is included in Python 2.6, you just need to import it.
0
>>> map(lambda x, y, z: (x, y, z), range(0, 3), range(3, 6), range(6, 9))
[(0, 3, 6), (1, 4, 7), (2, 5, 8)]

3 Comments

Now I understand why GvR didn't want map, reduce etc. in the language. :/
@karl-knechter, by the way, what is the preferred way to substitute reduce?
I think you're meant to write a for-loop explicitly. Note that I didn't say I agreed. ;)

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.