0

I want to create a list of items, some elements of which pointing to a single variable. As said variable changes value, the elements of the list that point to the variable should also change.

I.e, what I want to achieve is:

a = 5
myList = [1,2,a,4,a,6]
print(myList) # [1,2,5,4,5,6]
a = 6
print(myList) # [1,2,6,4,6,6]

Is there a way to achieve this?

Jckxxlaw
  • 391
  • 1
  • 4
  • 12

1 Answers1

1

It can't be done with immutable Python integers, but you can use a mutable list as a workaround:

a = [5]
myList = [1,2,a,4,a,6]
print(myList) # [1,2,5,4,5,6]
a[0] = 6
print(myList) # [1,2,6,4,6,6]

Output:

[1, 2, [5], 4, [5], 6]
[1, 2, [6], 4, [6], 6]
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251