News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Accessing the index in 'for' loops

posted on 2023-05-03 19:30     read(322)     comment(0)     like(29)     collect(2)


How do I access the index while iterating over a sequence with a for loop?

xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

Desired output:

item #1 = 8
item #2 = 23
item #3 = 45

solution


Use the built-in function enumerate():

for idx, x in enumerate(xs):
    print(idx, x)

It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.

Check out PEP 279 for more.



Category of website: technical article > Q&A

Author:qs

link:http://www.pythonblackhole.com/blog/article/145/5b0b067ea9b35a8b104f/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

29 0
collect article
collected

Comment content: (supports up to 255 characters)