-1

How can I write a loop in Python that behaves exactly like this JavaScript loop:

for (i = 0; i < cars.length; i++)

That is, I want the variable i to hold the value of the index of the character as I iterate over a string.

4 Answers4

0

This will work for what you would like to do

for i in range(len(cars)):
    print(i)  # 0, 1, 2, 3, 4...
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
0

Using the range function combined with len:

for i in range(len(cars)):
      ... cars[i]
miw
  • 776
  • 4
  • 11
0

Another option is to use enumerate:

for ii, car in enumerate(cars):
    print ii, car

assuming cars is a list like:

cars = ['a', 'b', 'c', 'd']

Then, the output is:

>>> 0 a
>>> 1 b
>>> 2 c
>>> 3 d
José Sánchez
  • 1,126
  • 2
  • 11
  • 20
0

Marginally better:

for i in xrange(len(cars)):
    print(i)

xrange is preferable to range in most cases. Best to get in the habit of using xrange.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80