Creating simultaneous loops in Python

I want to create a loop that makes 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
 eight
 ten
 12
 fourteen
 16
 18
+4
source share
5 answers

You can use zip to turn multiple lists (or iterations) 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 like izip (as mentioned above) on large sets. The advantage of zip is that it is built-in, and you do not need to import itertools - and whether this advantage is really subjective.

* Not only pairwise, but also n-wise. The length of the tuples will be the same as the number of iterations that you pass to zip .

+13
source

The itertools module contains izip , which combines iterators as desired:

 from itertools import izip for (i, k) in izip(xrange(0,10), xrange(0,10)): print i+k 
+10
source

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

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

+2
source

How 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

+2
source

What you want is two arrays and one loop, each iteration through each array, adding results.

0
source

All Articles