Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Declare two variable with the same values at the same time

a=[1,2,3]
b=[1,2,3]

Is there a way to do this on one line? (obviously not with ";")

a,b=[1,2,3] 

doesn't work because of

a,b,c=[1,2,3]

a=1 b=2 c=3

like image 714
Phoenix Avatar asked Nov 29 '22 07:11

Phoenix


2 Answers

In [18]: a,b=[1,2,3],[1,2,3]

In [19]: a
Out[19]: [1, 2, 3]

In [20]: b
Out[20]: [1, 2, 3]

you may also want to do this:

In [22]: a=b=[1,2,3]

In [23]: a
Out[23]: [1, 2, 3]

In [24]: b
Out[24]: [1, 2, 3]

but be careful that, a is b is True in this case, namely, a is just a reference of b

like image 141
zhangxaochen Avatar answered Dec 06 '22 11:12

zhangxaochen


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

each points to a different object

like image 20
gravetii Avatar answered Dec 06 '22 11:12

gravetii