I saw a one liner code that is claimed to remove duplicates from a sequence:
u = [x for x in seq if x not in locals()['_[1]']]
I tried that code in ipython (with Python 2.7), it gave KeyError: '_[1]'
Does ['_[1]']
mean something special in Python?
Python locals() function returns the dictionary of the current local symbol table. Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program.
globals() always returns the dictionary of the module namespace. locals() always returns a dictionary of the current namespace. vars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument.
The locals() method returns a dictionary with all the local variables and symbols for the current program.
locals()['_[1]']
is a way to access a reference to list comprehension (or generator) current result inside that list comprehension.
It is quite an evil, but can produce funny results:
>> [list(locals()['_[1]']) for x in range(3)]
[[], [[]], [[], [[]]]]
See more details here: the-secret-name-of-list-comprehensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With