Python iteration and iterator, and python

Source: Internet
Author: User
Tags integer numbers iterable

Python iteration and iterator, and python

We will learn important concepts of python iterations and iterators through simple and practical examples such as list iterator and xrange.

Iteratable

A sequence of objects, physical or virtual storage. List, tuple, strins, dicttionary, set, and generator objects can be iterated, and integer numbers cannot be iterated. If you are not sure which can be iterated or not, you need to use the built-in iter () in python to help.

>>> iter([1,2,3])<listiterator object at 0x026C8970>>>> iter({1:2, 2:4})<dictionary-keyiterator object at 0x026CC1B0>>>> iter(1234)Traceback (most recent call last): File "<pyshell#145>", line 1, in <module>  iter(1234)TypeError: 'int' object is not iterable

Iter () returns the listiterator object for the list and the dictionary-keyiterator object for the dictionary. Similar to other iteratable types, the iterator object is returned.

What if iter () is used for custom types? First, we define a String class:

class String(object): def __init__(self, val):  self.val = val def __str__(self):  return self.valst = String('sample string')

So, can st be iterated?

>>> iter(st)TypeError: 'String' object is not iterable

You may have a few questions:

How can custom types be iterated?
What exactly did iter () do?
Let's add the String class to find the answer.

class String(object):  def __init__(self, val):    self.val = val  def __str__(self):    return self.val  def __iter__(self):    print "This is __iter__ method of String class"    return iter(self.val) #self.val is python string so iter() will return it's iterator>>> st = String('Sample String')>>> iter(st)This is __iter__ method of String class<iterator object at 0x026C8150>

In the String class, a '_ iter _' method is required to convert the String type to iteratable, which means that 'iter 'calls 'iterable. _ iter __()'

Don't worry, not just adding the '_ iter ()' Method

class String(object):  def __init__(self, val):    self.val = val  def __str__(self):    return self.val  def __getitem__(self, index):    return self.val[index]>>> st = String('Sample String')>>> iter(st)<iterator object at 0x0273AC10>

'Itr' also calls 'iterable. _ getitem _ () ', so we use the' _ getitem _ 'method to make the String type iteratable.

If '_ iter _ ()' and '_ getitem _ ()' are used simultaneously in the String class, only '_ iter _' will work.

Automatic Iteration

The for loop is automatically iterated.

for x in iterable:  print x

Can we do this without a for loop?

def iterate_while(iterable):  index = 0  while(i< len(iterable)):    print iterable[i]    i +=1

This method works for list and string, but does not work for dictionary. Therefore, it is definitely not a python-type iteration and cannot simulate the for loop function. Let's look at the iterator first, and wait for the next time to overhead it.

Iterator

Let's talk about the iterator ...........

1. the iterator object will generate iteratable values during the iteration process. 'Next () 'or' _ next () _ 'is the method that the iterator uses to generate the next value.
2. It will issue a StopIteration exception after the iteration ends.
3. The 'iter () 'function returns the iterator object.
4. If the 'iter () 'function is used in the iterator object, it will return the object itself
Let's try to imitate the for loop.

def simulate_for_loop(iterable):  it = iter(iterable)  while(True): try:   print next(it) except StopIteration:   break>>> simulate_for_loop([23,12,34,56])23123456

We have read the iterable class before, and we know that iter will return the iterator object.

Now we try to understand the design of the iterator class.

class Iterator:  def __init__(self, iterable)    self.iterable = iterable  .  .  def __iter__(self): #iter should return self if called on iterator    return self  def next(self): #Use __next__() in python 3.x    if condition: #it should raise StopIteration exception if no next element is left to return      raise StopIteration

We have learned enough iterations and iterators and won't use them more deeply in python programs.

But for the purpose of learning, we will be here ....

List iterator

You may write this in the interview, so pay attention to it.

class list_iter(object):  def __init__(self, list_data):    self.list_data = list_data    self.index = 0  def __iter__(self):    return self  def next(self):  #Use __next__ in python 3.x    if self.index < len(self.list_data):      val = self.list_data[self.index]      self.index += 1       return val    else:      raise StopIteration()

Let's use 'list _ iter 'to define a list iterator.

class List(object):  def __init__(self, val):    self.val = val  def __iter__(self):    return list_iter(self.val)>>> ls = List([1,2,34])>>> it = iter(ls)>>> next(it)1>>> next(it)2>>> next(it)34>>> next(it)Traceback (most recent call last): File "<pyshell#254>", line 1, in <module>  next(it) File "<pyshell#228>", line 13, in next  raise StopIteration()StopIteration

Xrange

Start with a question -- is xrange an iterator or an iterator?

Let's take a look.

>>> x = xrange(10)>>> type(x)<type 'xrange'>

Key points:

1. 'iter (xrange (num) 'should be supported
2. If 'iter (xrange (num) 'returns the same object (xrange type), xrange is the iterator.
3. If 'iter (xrange (num) 'returns an iterator object, xrange is iteration.

>>> iter(xrange(10))<rangeiterator object at 0x0264EFE0>

It returns rangeiterator, so we can call it an iterator.

Let's use the least xrange function to implement our xrange.

Xrange_iterator

class xrange_iter(object):  def __init__(self, num):    self.num = num    self.start = 0  def __iter__(self):    return self  def next(self):    if self.start < self.num:      val = self.start      self.start += 1      return val    else:      raise StopIteration()

My xrange

class my_xrange(object):  def __init__(self, num):    self.num = num  def __iter__(self):    return xrange_iter(self.num)>>> for x in my_xrange(10): print x,0 1 2 3 4 5 6 7 8 9

The above is all the content of this article. I hope it will help you learn Python iterations and iterators.

Articles you may be interested in:
  • Example of how to use the python iterator
  • Python iterator and generator instance details
  • Python iterator instance analysis
  • Python iterator and generator use instance
  • Introduction to the iterator in Python
  • Introduction to Python iterators and generators
  • Describes Python iterators, generators, and related itertools packages.
  • Analysis on the usage of iterator in python
  • Python function Programming Guide (3): iterator details
  • Go deep into the iterator and generator in Python

Related Article

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.