6

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
wildfire
  • 119
  • 2
  • 4
  • 9
  • 1
    Is that the real output you're looking for, or is this a simplified version of the problem? – harto Sep 21 '09 at 03:02

5 Answers5

21

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.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
11

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
sth
  • 222,467
  • 53
  • 283
  • 367
  • 1
    And of course `zip()` is a built-in function in Python. And Python 3.x's `zip()` works exactly like `izip()` from Python 2.x – Daniel Pryden Sep 21 '09 at 03:06
2

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

2

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

LJM
  • 6,284
  • 7
  • 28
  • 30
0

What you want is two arrays and one loop, iterate over each array once, adding the results.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216