Expression Statements and In-Place Changes

This brings up a mistake that is common in Python work. Expression statements are often used to run list methods that change a list in-place:

>>> L = [1, 2]
>>> L.append(3)               # Append is an in-place change
>>> L
[1, 2, 3]

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

However, it’s not unusual for Python newcomers to code such an operation as an assignment statement instead, intending to assign L to the larger list:

>>> L = L.append(4)           # But append returns None, not L
>>> print(L)                  # So we lose our list!
None

This doesn’t quite work, though. Calling an in-place change operation such as append, sort, or reverse on a list always changes the list in-place, but these methods do not return the list they have changed; instead, they return the None object. Thus, if you assign such an operation’s result back to the variable name, you effectively lose the list (and it is probably garbage collected in the process!).

The moral of the story is, don’t do this. We’ll revisit this phenomenon in the section Common Coding Gotchas at the end of this part of the book because it can also appear in the context of some looping statements we’ll meet in later chapters.