QNA > H > How To Put A Variable Into An Array In Python

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 :

  1. >>> a = 23 
  2. >>> b = [1,2,3,a] 
  3. >>> print(b[3]) 
  4. 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.

  1. >>> a = 23 
  2. >>> b = [1,2,3,a] 
  3. >>> print(b[3]) 
  4. 23 
  5. >>> a = 17 
  6. >>> print(b[3]) 
  7. 23 

But - imagine that we use a mutable type (say another list)

  1. >>> a = [23] 
  2. >>> b = [1,2,3,a] 
  3. >>> print(b[3]) 
  4. [23] 
  5. >>> a[0] = 17 
  6. >>> print(b[3]) 
  7. [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 :

  1. >>> a = [23] 
  2. >>> b = [1,2,3,a] 
  3. >>> print(b[3]) 
  4. [23] 
  5. >>> a = [17] 
  6. >>> print(b[3]) 
  7. [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.

Di McKay

Quali sono le migliori applicazioni di sceneggiatura per Mac? :: How to give input to an array in Python
Link utili