python-by-example icon indicating copy to clipboard operation
python-by-example copied to clipboard

Explanations and warnings

Open thorwhalen opened this issue 5 years ago • 1 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)

thorwhalen avatar Sep 03 '19 15:09 thorwhalen

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 :)

sahands avatar Sep 09 '19 01:09 sahands