Phoenix
Phoenix

Reputation: 4656

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

Upvotes: 4

Views: 5034

Answers (6)

Rhand
Rhand

Reputation: 897

Edit: as found by DSM in order for the following lines to work you need to declare b as a list in order for my code to work (so this is no longer on one line, but I will leave it here as a reference). Changed the order as suggested by Paulo Bu

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

Old code:

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

This assigns the values to b and then copies all the values from b to a.

If you do it like this:

a=b=[1,2,3]

and then change

b[1] = 0

a would also be changed

Upvotes: 5

Potrebic
Potrebic

Reputation: 386

Note... this solution a=b=[1,2,3]

results in assigning the same (mutable) list to ivar's a and b. The original question shows 2 different lists being assigned to a & b.

This solution suffers the same problem:

>>> a,b = ([1,2,3],)*2
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]

Upvotes: 0

chronologos
chronologos

Reputation: 338

a,b = [1,2,3],[1,2,3] does it in one line and points to different objects.

a=b=[1,2,3] is clear but points to the same object.

Try a.pop(1) in both cases and you will see the difference.

Upvotes: 1

James Scholes
James Scholes

Reputation: 7926

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

Upvotes: 1

gravetii
gravetii

Reputation: 9654

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

each points to a different object

Upvotes: 7

zhangxaochen
zhangxaochen

Reputation: 34047

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

Upvotes: 11

Related Questions