Python iterations and iterators

Source: Internet
Author: User

Python iterations and iterators

Iterator

Iterator is also known as cursor. It is a software design pattern designed for programming. It can be accessed over and over container objects (such as linked lists or arrays, designers do not need to care about the implementation details of the memory allocation of container objects.

From Wikipedia

That is to say, the iterator is similar to a cursor, where it is stuck and where it can be used to access the elements of a iteratable object. At the same time, it is not only Python that has this feature. For example, this is also available in C ++ STL, such as vector <int>: iterator it. Next, let's talk about the iteratable objects and iterators in Python.

Iterable)

In Python, for is often used to traverse an object. In this case, the object to be traversed is an iteratable object, such as a common list and tuple. If an accurate definition is given, the _ iter _ method of an iterator can be returned as long as it is defined, you can also define the _ getitem _ method that supports subscript indexes (these double-underline methods will be fully explained in other chapters), so it is an iteratable object.

Python iterator)

The iterator is implemented through next (). Each call will return the next element. If there is no next element, a StopIteration exception is returned, therefore, all methods defined in this method are called iterators. You can use the following example to experience the iterator:

In [38]: s = 'ab'In [39]: it = iter(s)In [40]: itOut[40]: <iterator at 0x1068e6d50>In [41]: print it<iterator object at 0x1068e6d50>In [42]: it.next()Out[42]: 'a'In [43]: it.next()Out[43]: 'b'In [44]: it.next()---------------------------------------------------------------------------StopIteration               Traceback (most recent call last)<ipython-input-44-54f0920595b2> in <module>()----> 1 it.next()StopIteration:

Implement an iterator by yourself as follows (see the documentation on the official website ):

class Reverse:  """Iterator for looping over a sequence backwards."""  def __init__(self, data):    self.data = data    self.index = len(data)  def __iter__(self):    return self  def next(self):    if self.index == 0:      raise StopIteration    self.index = self.index - 1    return self.data[self.index]rev = Reverse('spam')for char in rev:  print char[output]maps

Generators)

Generator is the simplest and most powerful tool for constructing the iterator. Unlike normal functions, yield is used to replace return when a value is returned. Then yield automatically builds next () and iter (). Is it easy. For example:

def reverse(data):  for index in range(len(data)-1, -1, -1):    yield data[index]>>> for char in reverse('golf'):...   print char...flog

The best application scenario of the generator is: you do not want to allocate all the computed result sets to the memory at the same time, especially the result set contains loops. For example, xrange () instead of range () is used to print 1000000 rows in a loop, because the former returns the generator and the latter returns the list (the list consumes a lot of space ).

Help on built-in function range in module __builtin__:range(...)  range(stop) -> list of integers  range(start, stop[, step]) -> list of integers  Return a list containing an arithmetic progression of integers.  range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.  When step is given, it specifies the increment (or decrement).  For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!  These are exactly the valid indices for a list of 4 elements.class xrange(object) | xrange(stop) -> xrange object | xrange(start, stop[, step]) -> xrange object | | Like range(), but instead of returning a list, returns an object that | generates the numbers in the range on demand. For looping, this is | slightly faster than range() and more memory efficient.iter()

Converts an iteratable object to an iterator.

In [113]: s = 'abc'In [114]: s.next()---------------------------------------------------------------------------AttributeError              Traceback (most recent call last)<ipython-input-114-5e5e6532ea26> in <module>()----> 1 s.next()AttributeError: 'str' object has no attribute 'next'In [115]: it = iter(s)In [116]: it.next()Out[116]: 'a'

Generator expression

The only difference from the list derivation is that brackets are replaced with parentheses, as shown below:

In [119]: num = (i for i in range(10))In [120]: sum(num)Out[120]: 45

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.