Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does locals()['_[1]'] mean in Python?

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?

like image 439
Mert Nuhoglu Avatar asked Mar 09 '12 09:03

Mert Nuhoglu


People also ask

What does locals () mean 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.

What's the difference between globals () locals () and VARS ()?

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.

Which method returns a dictionary of the current local variables?

The locals() method returns a dictionary with all the local variables and symbols for the current program.


1 Answers

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.

like image 199
Roman Bodnarchuk Avatar answered Oct 06 '22 05:10

Roman Bodnarchuk