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.
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.
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.
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.
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 = {}, {}, {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With