So Ι have this python example:
In [1]: a=['1']
In [2]: b=a
In [3]: a[0] = int(a[0])
In [4]: type(a[0])
Out[4]: int
In [5]: type(b[0])
Out[5]: int
Why is b[0]
an int
and not a str
?
How can Ι fix the problem?
So Ι have this python example:
In [1]: a=['1']
In [2]: b=a
In [3]: a[0] = int(a[0])
In [4]: type(a[0])
Out[4]: int
In [5]: type(b[0])
Out[5]: int
Why is b[0]
an int
and not a str
?
How can Ι fix the problem?
This is because when you say b=a
, python doesn't create a new list for b
, with a copy of the elements in a
. Rather, b
is just another name for a
, and points to the same location in memory. Whatever memory address holds the stuff that we call a
is the same memory address that holds the stuff we call b
. Since only one entity may occupy a given memory address at a given time, a
and b
are effectively synonyms - like giving your friend a nickname.
This can be verified with id(...)
:
In [46]: a=['1']
In [47]: b=a
In [48]: id(a)==id(b)
Out[48]: True
Since lists are mutable, when you change the value of some index of a list, a new list is not created. Rather, the entity at the corresponding memory address of that list is replaced with a different entity.
So, back to that analogy about b=a
being like giving your friend a nickname: If your friend's name is John, and your nickname for him is "J" (how unimaginative! I clearly need some coffee). Then if John dyes his hair blue, well then so has J. J doesn't manage to retain his hair color despite John having done so.
Similarly, b
doesn't get to keep the '1'
, despite a
having changed.
Hope this helps
This is not a problem, it's how Python works.
When you create a variable in Python you are creating a variable name
which is a reference
to an object.
So what is happening here is that you are creating a list
object containing the string '1'
, and referencing this object with name a
.
This line b = a
will create a new name
b
which is also referencing the object ['1']
. Since list
is a mutable
object a[0] = int(a[0])
, will change in place
the type
of (string
) '1'
to (int
) 1
.
So because a
and b
are referencing the same object both will be type of int
.