Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: define multiple variables of same type?

Tags:

python

Probably a duplicate, but I can't find the answer by searching with these terms, at least.

Is there a quicker way to do this in Python?

level1 = {}
level2 = {}
level3 = {}

I've tried

level1 = level2 = level3 = {}

But that seems to create copies of the object, which isn't what I want. And

level1, level2, level3 = {}

throws an error.

like image 573
AP257 Avatar asked Dec 10 '10 17:12

AP257


People also ask

How do you assign multiple variables to the same value in Python?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

Can you define multiple variables in one line Python?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.

Can you define multiple variables in one line?

Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.


1 Answers

level1 = level2 = level3 = {}

Doesn’t create copies. It lets reference level{1-3} to the same object. You can use a list comprehension instead:

level1, level2, level3 = [{} for dummy in range(3)]

or more readable:

level1, level2, level3 = {}, {}, {}
like image 115
nils Avatar answered Nov 15 '22 09:11

nils