Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Python Basics: for i, element in enumerate(seq)..why/how does this work?

Hello I've found an intersting snippet:

seq = ["one", "two", "three"] #edited
for i, element in enumerate(seq):
    seq[i] = '%d: %s' % (i, seq[i])

>>> seq
['0: one', '1: two', '2: three']

I wonder how python is doing that.... for me element should be undefined...but obviously it isn't..what does python do here?

Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

enumerate essentially turns each element of the input list into a list of tuples with the first element as the index and the element as the second. enumerate(['one', 'two', 'three']) therefore turns into [(0, 'one'), (1, 'two'), (2, 'three')]

The bit just after the for pretty much assigns i to the first element and element to the second for each tuple in the enumeration. So for example in the first iteration, i == 0 and element == 'one', and you just go through the other tuples to get the values for the other iterations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...