Built-in Type Gotchas

In this and most of the next few chapters, we’ll include a discussion of common problems that seem to bite new users (and the occasional expert), along with their solutions. We call these gotchas—a degenerate form of “got you”—because some may catch you by surprise, especially when you’re just getting started with Python. Others represent esoteric Python behavior, which comes up rarely (if ever!) in real programming, but tends to get an inordinate amount of attention from language aficionados on the Internet (like us).[18] Either way, all have something to teach us about Python; if you can understand the exceptions, the rest is easy.

Assignment Creates References, Not Copies

We’ve talked about this earlier, but we want to mention it again here, to underscore that it can be a gotcha if you don’t understand what’s going on with shared references in your program. For instance, in the following, the list object assigned to name L is referenced both from L and from inside the list assigned to name M. Changing L in place changes what M references too:

>>> L = [1, 2, 3]
>>> M = ['X', L, 'Y']       # embed a reference to L
>>> M
['X', [1, 2, 3], 'Y']

>>> L[1] = 0                # changes M too
>>> M
['X', [1, 0, 3], 'Y']

Solutions

This effect usually becomes important only in larger programs, and sometimes shared references are exactly what you want. If they’re not, you can avoid sharing objects by copying them explicitly; for lists, you can always make a top-level copy by using an empty-limits ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.