Bernhard Heijstek
Bernhard Heijstek

Reputation: 2141

Declaring an empty list

I just noticed that declaring two empty lists as:

list1 = list2 = []

produced an entirely different result as compared to:

list1 = []
list2 = []

I don't this problem is related to the whole program as such, or that the result is important. Nevertheless here is the whole program. So is there any difference between the two ways of declaration?

Upvotes: 3

Views: 8732

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375574

When you say:

list1 = list2 = []

there is only one empty list, and you point both names list1 and list2 to it.

When you say:

list1 = []
list2 = []

there are two empty lists, each name gets a different one.

Keep in mind: assignment in Python never copies data. So two names can point to the same mutable value (list), and they will both see whatever changes are made to it.

Upvotes: 4

Chris Eberle
Chris Eberle

Reputation: 48775

list1 = list2 = []

can be written as:

list2 = []
list1 = list2

All you're doing is making an alias (effectively).

Upvotes: 6

GaretJax
GaretJax

Reputation: 7780

list1 = list2 = []

Assignes the same empty list instance ([]) to both list1 and list2. This is because object instances are assigned by reference.

You can do this instead:

list1, list2 = [], []

to assign two different lists two the two variables.

You can check it as follows:

list1 = list2 = []
print id(list1)  # Same as id(list2)
print id(list2)  # Same as id(list1)

list1, list2 = [], []
print id(list1)  # Different than id(list2)
print id(list2)  # Different than id(list1)

Upvotes: 10

Related Questions