sahands / python-by-example

Git repository for the "Python Language Features and Tricks You May Not Know Article" at http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Explanations and warnings

thorwhalen opened this issue · comments

Love this list.

Might there be a place for explanations and warnings linked to the techniques listed here?

For example, I wanted to contribute this:

Explanation: The [iter(a)] * k makes k copies of the same iterator. The address of the iterator (the 0x10c268a58) is the same. This means, that when you zip, iterating over the iterator in a round-robin fashion, you're consuming the same iterator, so you get the desired effect.

Note: Depends on a round-robin order of iterator consumption. Not sure if this is thread safe, since if python decides to implement parallelism for zip, this technique will fail.

>>> a = [1,2,3,4,5,6]
>>> w = [iter(a)] * 3
>>> w  # notice that each element of w has the same address: 0x10c268a58
[<list_iterator object at 0x10c268a58>, <list_iterator object at 0x10c268a58>, <list_iterator object at 0x10c268a58>]
>>> next(w[0]), next(w[1]), next(w[2])  # so interleaved consumption produces the desired effect
(1, 2, 3)

Thanks for the suggestion @thorwhalen. I prefer to keep the list very minimalistic since I believe part of why it's not just informative but also fun to read is that you have to reason through, for yourself, why the examples work the way they do. You're definitely welcome to publish a separate article that goes into detail explaining each item and going over caveats and limitations :)