Why the code:
lista=['1','2','3','4']
for element in lista:
element=int(element)
won't work while the following code works?
lista=['1','2','3','4']
for i in range(len(lista)):
lista[i]=int(lista[i])
Obs: I'm using Python 3.4.
Why the code:
lista=['1','2','3','4']
for element in lista:
element=int(element)
won't work while the following code works?
lista=['1','2','3','4']
for i in range(len(lista)):
lista[i]=int(lista[i])
Obs: I'm using Python 3.4.
In the first loop when you assign int(element)
to element
, it creates a new integer object and assigns it to name element
.
In the second loop, you are assigning int(lista[i])
to lista[i]
, which updates the i
th element of the list with that value.
This should help you understand it better.
>>> lista
['1', '2', '3', '4']
>>> i = lista[0] # i points to first element of lista
>>> i
'1'
>>> i = 'a' # Now i points to a new object 'a'
>>> lista # So lista remains as it was before
['1', '2', '3', '4']
>>> lista[0] = 'a' # Here we are replacing the first element of lista with 'a'
>>> lista
['a', '2', '3', '4']
Read up on immutable and mutable objects in Python.
BTW what you want to do here is this -
for i, element in enumerate(lista):
lista[i] = int(element)
Pythonic way to do this particular loop is to use list comprehension -
>>> lista=['1','2','3','4']
>>> lista = [int(element) for element in lista]
>>> lista
[1, 2, 3, 4]
This works because you assign each slot in the list to a new item:
lista=['1','2','3','4']
for i in range(len(lista)):
lista[i]=int(lista[i])
The below "works" but it doesn't do what you intend, because you're just assigning the elements to a variable name, then assigning a transformation to that name, and then not doing anything with it.:
lista=['1','2','3','4']
for element in lista:
element=int(element)
# try printing type(element) here to see that int actually does return an int