I need to do in Python the same as:
for (i = 0; i < 5; i++) {cout << i;}
but I don't know how to use FOR in Python to get the index of the elements in a list.
If you have some given list, and want to iterate over its items and indices, you can use enumerate():
for index, item in enumerate(my_list):
print index, item
If you only need the indices, you can use range():
for i in range(len(my_list)):
print i
range(len(my_list)) should be avoid? (for me, i would do enumerate but use only index).range(len(my_list)) (or xrange(len(my_list)) in Python 2.x).range() way: Just use print my_list[i].Just use
for i in range(0, 5):
print i
to iterate through your data set and print each value.
For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange
use enumerate:
>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
... print "%d: %s" % (index, val)
...
0: a
1: b
2: c
3: d
This?
for i in range(0,5):
print(i)
In additon to other answers - very often, you do not have to iterate using the index but you can simply use a for-each expression:
my_list = ['a', 'b', 'c']
for item in my_list:
print item
for i in range(5).