Python generator, iteratable object, iterator difference and connection, python Generator

Source: Internet
Author: User

Python generator, iteratable object, iterator difference and connection, python Generator

What is the relationship between generators, iteratable objects, and iterators?

Use a picture to summarize:

1. Generator

Definition Generator

Method 1:

// Unlike the list generator gen = [x * x for x in range (5)] gen = (x * x for x in range (5) print (gen) // Out: <generator object <genexpr> at 0x00000258DC5CD8E0>

Method 2:

def fib():  prev, curr = 0, 1  while True:    yield curr    prev, curr = curr, curr + prevf = fib()print(f) //Out:<generator object fib at 0x00000258DC5CD150>

After the definition is successful, we can use next () to access the next element of the generator.

print(next(gen)) //0print(next(gen)) //1...print(next(gen)) //16print(next(gen)) //StopIteration

However, we usually use for loop traversal.

for n in gen:  print(n) //0 1 4  9 16
2. iterator

Any object that implements the _ iter _ and _ next _ () methods is an iterator. _ Iter _ returns the iterator itself, __next _ returns the next value in the container. So the generator is a special iterator, which has both internal methods.

A custom iterator is as follows:

class Fib:  def __init__(self):    self.prev = 0    self.curr = 1   def __iter__(self):    return self   def __next__(self):    value = self.curr    self.curr += self.prev    self.prev = value    return valuef = Fib() count = 1 for n in f:  print(n)  count = count+1  if count>=10:    break//Out:1 1 2 3 5 8 13 21 34
3. iteratable objects

Objects such as list, tuple, set, dict, and str that can directly act on the for loop are called iteratable objects. The iteratable object implements the _ iter _ Method for returning the iterator.

demo = [1,2,3,4]print(isinstance(demo, Iterable)) //Trueiter_object = iter(demo)print(iter_object) //<list_iterator object at 0x00000258DC5EF748>

 

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.