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?

0

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Or anything else that's mutable. Perhaps a custom class would make the most sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.