Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to assign multiple variables to the same value?

This question may already been asked but I couldn't find a proper way to assign multiple variables to one value without linking them to it, so bear with me.

Example 1:

a = b = []
a.append('x')
> a = ['x']
> b = ['x']

Since I append 'x' to a I don't want to have it in b.


Example 2:

a, b = [[], []]
a.append('x')
> a = ['x']
> b = []

Works as expected but with multiple variables it becomes really ugly:

a, b, c, d, e, f, g, h, i j = [[], [], [], [], [], [], ...]

Example 3:

The default way

a = []
b = []
...

Same as example 2, it's not pretty with multiple variables.

I was wondering if something like this exists like in javascript?

a, b, c = [] #this actually gives a ValueError: not enough values to unpack

Any suggestions or am I limited to this?

Note: for some reason I have to avoid using dictionaries for this task. (limitation...)

like image 728
Hiroyuki Nuri Avatar asked Aug 21 '18 09:08

Hiroyuki Nuri


People also ask

Can multiple variables have the same value?

Again, remember that there is absolutely no algebraic rule that states that two or more variables can not equal the same number. Each point that the graph passes through represents an (X,Y) coordinate that would make the equation true.

Which is the proper way to assign a variable?

Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum .

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

int a, b, c; You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .


1 Answers

I would suggest you use fewer independent variables first and foremost. Any code that literally has a, b, c, d, e, ... in it should be refactored to something simpler.

Having said that:

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

The generator creates a new [] for as many items as you specify in the range.

like image 199
deceze Avatar answered Nov 15 '22 16:11

deceze