How to put a variable into an array in Python
Python doesn’t have arrays - it has lists
so given that you probably mean a list :
- >>> a = 23
- >>> b = [1,2,3,a]
- >>> print(b[3])
- 23
because everything is a reference that actual Python implementation is that a and b[3] both refer to the same integer object (23)
Because integers are immutable in Python (that means they can’t be changed), if you change a, then b[3] will still point to the integer object 23, and a will point to something else.
- >>> a = 23
- >>> b = [1,2,3,a]
- >>> print(b[3])
- 23
- >>> a = 17
- >>> print(b[3])
- 23
But - imagine that we use a mutable type (say another list)
- >>> a = [23]
- >>> b = [1,2,3,a]
- >>> print(b[3])
- [23]
- >>> a[0] = 17
- >>> print(b[3])
- [17]
So again - after line 2 - the list element b[3] contains a reference to the same list object that a refer to.
on line 5 we change the contents of the list referred to by a; but because b[3] also pointed to that list object - b[3] also now refers to the changed object. You could also use append, insert, pop, del to change the list contents.
If you do this though :
- >>> a = [23]
- >>> b = [1,2,3,a]
- >>> print(b[3])
- [23]
- >>> a = [17]
- >>> print(b[3])
- [23]
Now In line 5 the a = [17] is n’t changing the contents of an existing object - it is creating a brand new object so b[3] still refers to the old object : [23], while a now refers to the new object [17]
I hope this helps.