Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

Python Variables: Why Two Names Can Change the Same List

In Python, assignment binds another name to an object; it does not copy it. Learn why mutable lists can appear to change through both names, and how copying works.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If y = x is followed by a change to y and x appears to change too, the reason is usually that both names refer to the same mutable object. Assignment creates another reference; it does not copy the object.

What happens when you write y = x?

Python makes y refer to the object that x currently refers to. There is one object and two names for it. The Python Software Foundation explains this directly in its Programming FAQ.

As an Amazon Associate I earn from qualifying purchases.

x = []
y = x
y.append(10)
print(x)  # [10]
print(y)  # [10]

append changes the list in place. Since both names refer to that list, looking through either name reveals the added value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does changing an integer behave differently?

Integers are immutable: an operation does not change the existing integer object. In this example, addition produces a value and the assignment makes x refer to it; y still refers to the original value.

x = 5
y = x
x = x + 1
print(x)  # 6
print(y)  # 5

This is rebinding, not a shared mutation. Rebinding changes the object a name refers to. Mutation changes an object itself, which is why it can be observed through every name referring to that object.

Which Python objects can be changed in place?

Lists, dictionaries, and sets are mutable: operations can change their contents without replacing the object. Numbers, strings, and tuples are immutable with respect to their own value or structure. The Python data model describes these distinctions.

Immutability applies to an object’s own structure, not necessarily to everything it contains. A tuple cannot have its item slots reassigned, but it can contain a mutable object such as a list:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
items = [1]
t = (items,)
t[0].append(2)
print(t)  # ([1, 2],)

The tuple itself was not changed; the list it refers to was.

How can you tell whether an operation mutates or creates a value?

Look at the operation and the type. In-place list methods such as append and sort change the existing list. By contrast, y = y + [10] makes a new list and rebinds y; sorted(y) returns a new sorted list and leaves the original unchanged. Many mutating methods return None, rather than returning the modified object.

Augmented assignment is type-dependent. For a list, += can update the existing list in place; for an integer, it produces a new value and rebinds the name. Do not assume that the same operator has identical mutation behavior for every type.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do you make a copy instead of another reference?

Choose the copy depth based on whether nested objects should remain shared. A shallow copy creates a distinct outer object but retains references to objects inside it. A deep copy recursively copies nested objects, subject to the objects’ copying behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import copy

x = [[1]]
y = copy.copy(x)       # new outer list; inner list is shared
z = copy.deepcopy(x)   # nested list is copied too

For a shallow copy, changing the outer list does not change the other outer list, but mutating the shared inner list is visible through both. Use copy.deepcopy() when nested objects should not remain shared and recursive copying is appropriate.

To check whether two names refer to the identical object, use x is y. The built-in id() can also provide an object’s identity value during a program’s lifetime, but equality with == answers a different question: whether values compare equal.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.