The difference between lists and iterators in python (well understood version)

Iterator: (Note that iterators are a feature of python3)

Iteration is one of the most powerful features of Python and is a way of accessing the elements of a collection.

An iterator is an object that remembers where to traverse.

Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.

Iterators have two basic methods: iter() and next() .

String, list or tuple objects can all be used to create iterators.

eg:

list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
print (next(it))   # 输出迭代器的下一个元素 
# 输出 1

To give an example: the map function returns an iterator, what exactly is going on?

(There is also the zip function, which also returns an iterator, which is to save memory. In order to get a list, you can use the list() method to convert it into a list)

>>> def square(x) : # Calculate the square number
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # Calculate the square of each element of the list
<map object at 0x100d3d550> # return iterator

As can be seen from the figure, what is returned is the address of the header element of the iterator.

At this time, you only need to traverse this iterator to return all the results:

 
>>> list(map(square, [1,2,3,4,5])) # Use list() to convert to list
[1, 4, 9, 16, 25]

The difference between lists and iterators:

  • No matter how many times the list is traversed, the header position is always the first element
  • After the iterator traverses, it no longer points to the original header position, but to the next position of the last element

Guess you like

Origin blog.csdn.net/candice5566/article/details/123214196