Python Note 1 – iterator

This post is a quick recap on what I’ve learned about:
1. List comprehension
2. Generators
3. Iterable and iterator

List comprehension

  • We can create a list in this way:
lc = [x_expression
for x in iterable if condition]
lc = [x_y_expression
for x in iterable if condition
for y in iterable if condition]
  • Note that list comprehension is not a step-by-step in-place substitution. Instead, it puts together a new list by the rule and links it to our variable name “lc”.

Generators

  • Likewise, we can create generators in this way:
g = (x_expression
for x in iterable if condition)
g = (x_y_expression
for x in iterable if condition
for y in iterable if condition)
  • Function with yield before return returns a generator object.
    When such a generator object is iterated, it runs the code between the beginning and the first yield, the first yield and the second yield , so on so forth.

Iterable and iterators

  • Objects that can be iterated are iterables.
    Dictionaries and generators are also iterables.
  • Objects that can be iterated and support function next(iter) to find the next element are iterators.
    Iterator includes generators and some customized objects.
    A customized iterator must have __iter__ and __next__.
  • iter(iterable) returns its according iterator.
  • The benefit of an iterator is that every element is computed when called and there no need for space to store all the elements.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: