简体   繁体   中英

Initialization of multiple empty lists in Python

What is the correct way to initialize a bunch of variables to independent empty lists in Python 3?

>>> (a, b) = ([],)*2
>>> a.append([2,3])
>>> a
[[2, 3]]
>>> b
[[2, 3]]
>>> b.append([2,3,])
>>> b
[[2, 3], [2, 3]]
>>> a
[[2, 3], [2, 3]]


>>> (a, b) = ([]  for _ in range(2))
>>> a.append([2,3])
>>> a
[[2, 3]]
>>> b
[]
>>> b.append([2])
>>> b
[[2]]
>>> a
[[2, 3]]

Why the first attempt does not allocate a , b independently in memory?

Why the first attempt does not allocate a, b independently in memory? because they refer to same address in memory.

(a, b) = ([],)*2
print(id(a))
print(id(b))
# 4346159296
# 4346159296
(a, b) = ([]  for _ in range(2))
print(id(a))
print(id(b))
# 4341571776
# 4341914304

You can initialize them as the following.

a = b = []
a = [2]
b = [2, 3]
print(a, b)

Why the first attempt does not allocate a, b independently in memory?

Because you are using same list to define several variables. It is something like:

list1 = []
var1, var2 = list1, list1

In your second case you are using comprehension which is creating new lists every iteration.

You can have a look at this example

list1 = [1, 2, 3]
a = [val for val in list1]
b = [val for val in list1]
c, d = ([list1]) * 2
print(f"{a=}")
print(f"{b=}")
print(f"{c=}")
print(f"{d=}")
print("Append something")
a.append("a append")
list1.append("list1 append")
print(f"{a=}")
print(f"{b=}")
print(f"{c=}")
print(f"{d=}")

Output:

a=[1, 2, 3]
b=[1, 2, 3]
c=[1, 2, 3]
d=[1, 2, 3]
Append something
a=[1, 2, 3, 'a append']
b=[1, 2, 3]
c=[1, 2, 3, 'list1 append']
d=[1, 2, 3, 'list1 append']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM