0

I want to assign empty list to multiple variables. I have tried these:

# method 1
a = b = []

# method 2
c, d = [], []


print('\nBefore')
print(f'a: id={id(a)} value={a}')
print(f'b: id={id(b)} value={b}')
print(f'c: id={id(c)} value={c}')
print(f'd: id={id(d)} value={d}')

b = [1,2,5]
c = [6,4,2]

print('\nAfter')
print(f'a: id={id(a)} value={a}')
print(f'b: id={id(b)} value={b}')
print(f'c: id={id(c)} value={c}')
print(f'd: id={id(d)} value={d}')

The difference, that I can see, is that both a and b point to the same location at initialize but changes after assignments. What is the Pythonic way to assign empty list to multiple variables?

Edit: Question is not about how to assign multiple variables but what is the Pythonic way(better way) of assigning multiple variables.

8
  • a,b = list(), list() is you need the lists to be separate objects (working around interning) Commented May 31, 2019 at 17:04
  • 1
    I read that [] is better that list()! As list() evokes a function Commented May 31, 2019 at 17:05
  • 1
    My fav is a, b = [[] for _ in range(2)] Commented May 31, 2019 at 17:05
  • I am not sure it is duplicated as the question is which way is better and not how to assign variables Commented May 31, 2019 at 17:06
  • 2
    @PraysonW.Daniel Depends on how you define "better". If you want all the variables to point to the same list object, use your first method. If you want them all to be separate list objects, use the second (or any of the others in the dupe target). Commented May 31, 2019 at 17:08

1 Answer 1

1

Simplest solution:

a = b = c = d = []

Rather pythonic in my opinion, although this will be the same reference o a singular list object (a.append("foo") also mutates b, c, and d).

To initialize completely separate list objects, as pointed out in the comments:

a, b, c, d = ([] for _ in range(4))

or

a, b, c, d = [], [], [], []     # or list(), list(), list(), list()

It's not hugely pretty, I agree. But do you really need four separate list variables? Here's what I think you should do:

lists = ([] for _ in range(4))

Then you can access the different lists using lists[0] to lists[3].

Sign up to request clarification or add additional context in comments.

2 Comments

a = b = [] means that any inplace change to a will appear in b as well. b is just another 'name' for the 'a' object.
@hpaulj I think that was made pretty clear by the sentences immediately following it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.