Accessing the index in for loops

0 votes

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?

Dec 16, 2020 in Python by Rajiv
• 8,910 points
378 views

1 answer to this question.

0 votes

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)

answered Dec 16, 2020 by Gitika
• 65,910 points

Related Questions In Python

+1 vote
1 answer

Accessing the index in 'for' loops?

Using an additional state variable, such as ...READ MORE

answered Aug 28, 2018 in Python by Priyaj
• 58,090 points
382 views
0 votes
1 answer

Accessing the index in 'for' loops?

Use enumerate to get the index with ...READ MORE

answered Mar 13, 2019 in Python by Trisha
479 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
2,035 views
0 votes
1 answer

Get index in for loop

Use enumerate(): for index, value in enumerate(array): ...READ MORE

answered Apr 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
358 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,061 views
0 votes
1 answer
0 votes
1 answer

I've been trying to run this code, but the error says "Expected an indented block" for the line, " word_as_list[index] = guess."

Hi, @Paradox, The error message IndentationError: expected an indented ...READ MORE

answered Nov 21, 2020 in Python by anonymous
• 65,910 points
839 views
0 votes
1 answer

How to find the index of an item in a list?

One thing that is really helpful in ...READ MORE

answered Dec 3, 2020 in Python by Gitika
• 65,910 points
1,180 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP