Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Simultaneous Loops in Python

Tags:

python

loops

I want to create a loop who has this sense:

for i in xrange(0,10):
for k in xrange(0,10):
     z=k+i
     print z

where the output should be

0
2
4
6
8
10
12
14
16
18
like image 928
wildfire Avatar asked Sep 21 '09 02:09

wildfire


People also ask

How do you use two loops simultaneously?

The solution is very simple,use the tuple & zip function. Map function is 1 liner representation of for loop which can accept multiple arguments.

Can you loop through two lists at once Python?

Use the izip() Function to Iterate Over Two Lists in Python It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.


4 Answers

You can use zip to turn multiple lists (or iterables) into pairwise* tuples:

>>> for a,b in zip(xrange(10), xrange(10)):
...     print a+b
... 
0
2
4
6
8
10
12
14
16
18

But zip will not scale as well as izip (that sth mentioned) on larger sets. zip's advantage is that it is a built-in and you don't have to import itertools -- and whether that is actually an advantage is subjective.

*Not just pairwise, but n-wise. The tuples' length will be the same as the number of iterables you pass in to zip.

like image 133
Mark Rushakoff Avatar answered Nov 15 '22 09:11

Mark Rushakoff


The itertools module contains an izip function that combines iterators in the desired way:

from itertools import izip

for (i, k) in izip(xrange(0,10), xrange(0,10)):
   print i+k
like image 30
sth Avatar answered Nov 15 '22 09:11

sth


You can do this in python - just have to make the tabs right and use the xrange argument for step.

for i in xrange(0, 20, 2); print i

like image 43
Aarlo Stone Fish Avatar answered Nov 15 '22 08:11

Aarlo Stone Fish


What about this?

i = range(0,10)
k = range(0,10)
for x in range(0,10):
     z=k[x]+i[x]
     print z

0 2 4 6 8 10 12 14 16 18

like image 44
LJM Avatar answered Nov 15 '22 09:11

LJM