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.
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.
This will work for what you would like to do
for i in range(len(cars)):
print(i) # 0, 1, 2, 3, 4...
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
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
.