Accessing the index in 'for' loops?

Asked : Nov 17

Viewed : 31 times

How do I access the index in a for loop like the following?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))

I want to get this output:

item #1 = 8
item #2 = 23
item #3 = 45
item #4 = 12
item #5 = 78

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

loops python list 

Nov 17

5 Answers

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

for idx, val in enumerate(ints):
    print(idx, val)

Check out PEP 279 for more.

answered Jan 18


It's pretty simple to start it from 1 other than 0:

for index, item in enumerate(iterable, start=1):
   print index, item  # Used to print in python<3.x
   print(index, item) # Mirate print() after 3.x+

answered Jan 18


First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:

for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)

To get the value of an index use

list[index]

answered Jan 18


Access Index in Python's for Loop?

The easiest, and most popular method to access the index of elements in a for loop is to go through the list's length, increasing the index. On each increase, we access the list on that index:

my_list = [3, 5, 4, 2, 2, 5, 5]

print("Indices and values in my_list:")

for index in range(len(my_list)):
    print(index, my_list[index], end = "\n")

Here, we don't iterate through the list, like we'd usually do. We iterate from 0..len(my_list) with the index. Then, we use this index variable to access the elements of the list in order of 0..n, where n is the end of the list.

This code will produce the output:

Indices and values in my_list:
0 3
1 5
2 4
3 2
4 2
5 5
6 5

answered Jan 18


One of the simplest ways to access indices of elements in a sequence in for loops is by traversing through the length of the sequence using an iterator, increasing it by one and accessing the element at that particular sequence.

Consider the below list

list= [1,3,5,7,9]

Example:

list= [1,3,5,7,9]

for index in range(len(list)):
   print("Index: "+str(index)+ " , " "Value: "+str(list[index])

answered Jan 18


Login and Submit Your Answer
Browse other questions tagged  loops  python  list or ask your own question.