Home > front end >  Initialization of multiple empty lists in Python
Initialization of multiple empty lists in Python

Time:05-14

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?

CodePudding user response:

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

CodePudding user response:

You can initialize them as the following.

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

CodePudding user response:

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']
  • Related