0

Is it possible to iterate through multiple lists and return arguments from different lists within the same loop?

I.e., Instead of -

For x in trees:
  Print(x) 
For y in bushes:
  Print(y)

Something like -

For x,y in trees,bushes:
  Print(x +"\n"+ y)
conma293
  • 45
  • 2
  • 9
  • And also http://stackoverflow.com/questions/126524/iterate-a-list-as-tuples-in-python and http://stackoverflow.com/questions/1210396/how-do-i-iterate-over-the-tuples-of-the-items-of-two-or-more-lists-in-python and probably many more ... :-) – mgilson Sep 10 '15 at 21:36

2 Answers2

8

You can simply use zip or itertools.izip:

for x, y in zip(trees, bushes):
  print x, y
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    python2.x also has [`future_builtins.zip`](https://docs.python.org/2/library/future_builtins.html#future_builtins.zip) which is handy for writing code that works on python2.x and 3.x (Just guard the import statement with a `try: ... except ImportError: pass` suite). – mgilson Sep 10 '15 at 21:34
  • @mgilson Good point. Python 2.x where x >= 6. – juanchopanza Sep 10 '15 at 21:42
  • Oh, did python exist in earlier versions than that ;-). I can't seem to remember ... – mgilson Sep 10 '15 at 21:45
  • @mgilson I still run into systems that are on older versions than 2.6. It is painful. – juanchopanza Sep 10 '15 at 21:46
2

You can use zip():

a=['1','2','2']
b=['3','4','5']

for x,y in zip(a,b):
     print(x,y)

output:

1 3

2 4

2 5

jlnabais
  • 829
  • 1
  • 6
  • 18