0

I have working on JavaScript, C#, Java for so long. In these we can initiate multiple variables with same value;

var a, b, c = 0

OR

int a, b, c = 0

Trying to do the same in python but unable to do it. Tried many things like;

a = b = c = 0

its working with int but with list

enter image description here

but it creates reference to other variable.

Thanks in advance

Farhan
  • 1,445
  • 16
  • 24
  • In Python all variables are objects, therefore references to one thing – Petronella Feb 05 '20 at 13:37
  • Are you trying to apply this to mutable objects? In this exact case, it shouldn't matter that `a`, `b` and `c` all reference the same number since `0` is immutable. – Carcigenicate Feb 05 '20 at 13:38
  • @Petronella , Updated my question of what I am trying to – Farhan Feb 05 '20 at 13:55
  • @Carcigenicate I want to mutate value for each variable separately after declaring it – Farhan Feb 05 '20 at 13:59
  • Because List is an object, a,b and c are references to the same address where this one list is stored. So you don't have 3 separate lists on 3 separate disk addresses with 3 references, each for a list. – Petronella Feb 05 '20 at 14:13
  • See this link:https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior. It essentially explains that `int` is immutable; so in your case, 0 is 0 forever. `Lists` behave differently because they are mutable. – gmdev Feb 05 '20 at 14:18
  • @Petronella, Yeah I get that but without creating reference to each other. – Farhan Feb 05 '20 at 14:20
  • @gmdev `a,b,c = [],[],[]` is ok but we want to mimic `a,b,c = []` of java and other programming languages without creating references – Farhan Feb 05 '20 at 14:27

2 Answers2

0

I think the closest you could get is to repeat the list via some means. Since Python unfortunately doesn't have an equivalent to Clojure's repeatedly, you could do something with a list comprehension:

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

Or, create your own generator to help out here:

def repeatedly(f):
    while True:
        yield f()

a, b, c, *_ = repeatedly(list)

The *_ here is unfortunately required to hold the rest of the infinite list.

The point though is, you must explicitly create multiple lists through some means. A copy will never be created via assignment in Python. If you want multiple lists, you must create multiple lists.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

I reckon you just want brevity, this might be something:

(a,b,c) = ( [] ,[], [] )
a.append(1)
print(a)
print(b)

output:

[1]
[]
Petronella
  • 2,327
  • 1
  • 15
  • 24
  • its the same as `a,b,c = [], [], []` – Farhan Feb 05 '20 at 14:57
  • what are you trying to do, then? With int it works because it is a primitive, the size in bits is the same size of the reference value. With anything else than primitives putting one potato to three one bags will not work – Petronella Feb 05 '20 at 15:03