Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this Python magic?

If you do this {k:v for k,v in zip(*[iter(x)]*2)} where x is a list of whatever, you'll get a dictionary with all the odd elements as keys and even ones as their values. woah!

>>> x = [1, "cat", "hat", 35,2.5, True]
>>> d = {k:v for k,v in zip(*[iter(x)]*2)}
>>> d
{1: "cat", "hat": 35, 2.5: True}

I have a basic understanding of how dictionary comprehensions work, how zip works, how * extracts arguments, how [iter(x)]*2 concatenates two copies of the list, and so I was expecting a one-to-one correspondence like {1: 1, "cat": "cat" ...}.

What's going on here?

like image 668
Lion Wild Avatar asked Sep 26 '26 00:09

Lion Wild


1 Answers

This is an interesting little piece of code for sure! The main thing it utilizes that you might not expect is that objects are, in effect, passed by reference (they're actually passed by assignment, but hey). iter() constructs an object, so "copying" it (using multiplication on a list, in this case) doesn't create a new one, but rather adds another reference to the same one. That means you have a list where l[0] is an iterator, and l[1] is the same iterator - accessing them both accesses the very same object.

Every time the next element of the iterator is accessed, it continues where it last left off. Since elements are accessed alternately between the first and second elements of the tuples that zip() creates, the single iterator's state is advanced across both elements in the tuple.

After that, the dictionary comprehension simply consumes these pair tuples as they expand to k, v - as they would in any other dictionary comprehension.

like image 148
obskyr Avatar answered Sep 27 '26 14:09

obskyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!