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

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

bar = [42]
def foo():

>>> print bar

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!!

It appears completely incorrect to me.

bar = [42]
def foo():

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

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():

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

test() >> executes test() code

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

The same example in your code seems to have different 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)
print bar

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!