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
2.5k views
in Technique[技术] by (71.8m points)

iteration - What is the use of iter in python?

What is the use of using the iter function in python?

Instead of doing:

for i in range(8):
  print i

I could also use iter:

for iter in range(8):
  print iter
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First of all: iter() normally is a function. Your code masks the function by using a local variable with the same name. You can do this with any built-in Python object.

In other words, you are not using the iter() function here. You are using a for loop variable that happens to use the same name. You could have called it dict and it would be no more about dictionaries than it is about Guido's choice of coffee. From the perspective of the for loop, there is no difference between your two examples.

You'd otherwise use the iter() function to produce an iterator type; an object that has a .next() method (.__next__() in Python 3).

The for loop does this for you, normally. When using an object that can produce an iterator, the for statement will use the C equivalent of calling iter() on it. You would only use iter() if you were doing other iterator-specific stuff with the object.


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

...