Iterators and 10 other Python 3 upgrade reasons

I ran into a very interesting presentation from Aaron Meurer titled:

10 awesome features of Python that you can’t use because you refuse to upgrade to Python 3 – source

Aaron gave the presentation on April 9, 2014 at the Austin Python User Group (APUG). Austin is a bit too far away from Amsterdam to just go there and to see the talk, but I am glad we get access to his slides, because they are awesome! Below I quote the slides on “iterator” improvements of Python 3 that he explains exceptionally well.

Why iterators are good

Aaron Meurer lists the advantages of using iterators (and generators) on slide 58:

  • Only one value is computed at a time. Low memory impact (see range example below).
  • Can break in the middle. Don’t have to compute everything just to find out you needed none of it. Compute just what you need. If you often don’t need it all, you can gain a lot of performance here.
  • If you need a list (e.g., for slicing), just call list() on the generator.
  • Function state is “saved” between yields.
  • This leads to interesting possibilities, a. la. coroutines…

Why Python 2 was not so good

Then he states that in Python 2 things were not that good (slide 42-50), since you could accidentally forget to use iterators:

  • Don’t write range or zip or dict.values or …. If you do…
  • python_iterator
    (click to enlarge)
  • Instead write some variant (xrange, itertools.izip, dict.itervalues, …).
  • Inconsistant API anyone?

Why Python 3 is much better

In  slide 51 Aaron Meurer states that in Python 3 things have improved and iterators are used by default. He explains that you can still get a list if you need one:

  • In Python 3, range, zip, map, dict.values, etc. are all iterators.
  • If you want a list, just wrap the result with list.
  • Explicit is better than implicit.
  • Harder to write code that accidentally uses too much memory, because the input was bigger than you expected.

The 10 other features

Interested in the 10 other features “you can’t use because you refuse to upgrade to Python 3”? Look at awesome presentation by Aaron Meurer on his GitHub account:


2 thoughts on “Iterators and 10 other Python 3 upgrade reasons”

  1. @tersmitten: Great article! Thank you for sharing it.

Leave a Reply

Your email address will not be published. Required fields are marked *