Python: Common Newbie Mistakes, Part 2

The focus of this part is an area of problems where scoping in Python is misunderstood. Usually, when we have global variables (okay, I’ll say it because I have to - global variables are bad), Python understands it if we access them within a function:


This is a companion discussion topic for the original entry at http://amir.rachum.com/blog/2013/07/09/python-common-newbie-mistakes-part-2/

Thanks for the nice series, I keep learning from it! The example:

bar = [42]
def foo():
bar.append(0)

>>> print bar
[42]

however is wrong (actually it's correct but doesn't make sense), as the foo() part is missing.

Open your eyes man ... foo() is used in the next code snippet!!

z_e_r_o
It appears completely incorrect to me.

bar = [42]
def foo():
....bar.append(0)

>>> bar
[42]
>>> foo()
>>> bar
[42, 0]

o_n_e_!!
You open your eyes man, lol

"The first misconception is that Python, being an interpreted language
(which is awesome, I think we can all agree), is executed line-by-line.
In truth, Python is being executed statement-by-statement. "

Dude, what are you smoking?

Hi Amir,
Great post.

When I try the following code:
bar = [42]

def test():
bar.append(1)

print(bar) >> prints "[42]"

test() >> executes test() code

print(bar) >> prints "[42, 1]"

The same example in your code seems to have different results...is this a mistake?

It's correct, but it doesn't do a single thing with foo(). Yes, the best way would be print bar, foo(), print bar

Your blog seems to be blocked in Facebook. You might want to check that out.

I have to admit I made a mistake, and your comment was valid ... The third code snippet should call 'foo()' then call 'print(bar)' ... And it turns out that bar is modified to [42, 0] (test on both Python-2 and 3).

In what way is it blocked? I shared it without any problems.

I understand the problem with this explanation, but it's the best novice-friendly way I could come up with to explain my point.

bar = [42]
def foo(): bar.append(0)
foo()
print bar
[42]

Is still wrong. It should print [42, 0]

The last code segment has wrong indentation.
The "def foo(): ..." block should be indented.

The first misconception is that python is an interpreted language. Python is a compiled language just like Java. Even when you run a code in the "interpreter", this code is actually compiled to byte code and the byte code is then executed in a virtual machine!