开发者

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?


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)


list1 = list2 = []

can be written as:

list2 = []
list1 = list2

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜