同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
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]
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.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏
