0

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?

2
  • Does this answer your question? Python - Initializing Multiple Lists/Line Commented May 13, 2022 at 10:41
  • not with regards to the latter part Commented May 13, 2022 at 10:43

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can initialize them as the following.

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

1 Comment

>>> a = b = [] >>> a.append(2) >>> a [2] >>> b [2]
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.