Skip to content

Instantly share code, notes, and snippets.

@uucidl
Created March 15, 2016 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uucidl/2a51ffcae6f72d77d4d0 to your computer and use it in GitHub Desktop.
Save uucidl/2a51ffcae6f72d77d4d0 to your computer and use it in GitHub Desktop.
Something insane I did not know about python
H:\temp>python
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'hello'
>>> print a
hello
>>> words = [a for a in ['one', 'two', 'three']]
>>> print words
['one', 'two', 'three']
>>> print a
three
>>>
@uucidl
Copy link
Author

uucidl commented Mar 15, 2016

I can understand mechanically why it does that, but that was really unexpected to me. I always assumed the list comprehension like feature would introduce a new scope where the variables would live.

It basically treats the [a for a in [...]] syntax just as sugar for a surrounding for loop, which trashes the other variable

for a in [...]:

@sixohsix
Copy link

Yeah that's fun. Basically only def and class introduce scopes, nothing else (I think). The behavior above is sort of a feature since you can search for something in a loop and access it after.

And then you're like "what if I get to the end of a loop and nothing matched?" To counteract that for loops can have an "else" clause. :)

The 90's were weird.

@uucidl
Copy link
Author

uucidl commented Mar 15, 2016

Yeah this reminds me a lot of JavaScript. I thought python had more scopes.. I guess I'll liberally enclose most of my scopes in local functions from now on, unless it's at the expense of clarity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment