2

Possible Duplicate:
Accessing the index in Python for loops

I wonder: does Python have something like?

for (i=0; i < length; i += 1){ .... }

Of course, I might say

i = 0
for item in items:
 #.....
 i += 1

but I think there should be something similar to for(i = 0;...), shouldn't it?

Community
  • 1
  • 1
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

3 Answers3

11

Use the enumerate() function:

for i, item in enumerate(items):
     print i, item

or use range():

for i in range(len(items)):
     print i

(On python 2 you'd use xrange() instead).

range() let's you step through i in steps other than 1 as well:

>>> list(range(0, 5, 2))
[0, 2, 4]
>>> list(range(4, -1, -1))
[4, 3, 2, 1, 0]

You usually don't need to use an index for sequences though; not with the itertools library or the reversed() function; most usecases for 'special' index value ranges are covered:

>>> menu = ['spam', 'ham', 'eggs', 'bacon', 'sausage', 'onions']
>>> # Reversed sequence
>>> for dish in reversed(menu):
...     print(dish)
... 
onions
sausage
bacon
eggs
ham
spam
>>> import itertools
>>> # Only every third
>>> for dish in itertools.islice(menu, None, None, 3):
...     print(dish)
... 
spam
bacon
>>> # In groups of 4
>>> for dish in itertools.izip_longest(*([iter(menu)] * 4)):
...     print(dish)
... 
('spam', 'ham', 'eggs', 'bacon')
('sausage', 'onions', None, None)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Attempt for that this is a deliberate language choice. The majority of times does loop through numbers in lower level languages, those numbers are used as indexes in a sequence. For the cases one does actually needs the numbers, one should use the range built-in function - which returns an iterable with the desired range([start], end, [step]) input values.

More often, one does need both the items of a sequence and their index, in this case, one should use the builtn enumerateinstead:

for index, letter in enumerate("word"):
     print index, letter

And finally, in C and derived languages (Java, PHP, Javascript, C#, Objective C), the for Syntax is just some (very rough) syntax sugar to a while loop - and you can just write the same while loop in Python.

Instead of: for (start_expr, check_expr, incr_expr) { code_body} you do:

start_expr
while check_expr:
    code_body
    incr_expr

It works exactly the same.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
0
for i in range(length):
    #do something

What range is.

ovgolovin
  • 13,063
  • 6
  • 47
  • 78