-1

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.

  • ```element``` is a copy of the value, not a reference to it. – Lucas Virgili Jul 11 '14 at 22:49
  • @LucasVirgili at which stage? In the `for` loop assignment, that claim is *precisely wrong*. After the `int` assignment, it's nearly right. – jonrsharpe Jul 11 '14 at 22:52
  • Why did you think the first version *would* work? You can see the difference between the two versions, so why do *you think* the first doesn't work? – jonrsharpe Jul 11 '14 at 22:53
  • @jonrsharpe only being different don't explain nothing. Besides, if i could see the difference between the two versions, i wouldn't even make this question. – user3674171 Jul 12 '14 at 02:40

2 Answers2

1

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 ith 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]
Community
  • 1
  • 1
ronakg
  • 4,038
  • 21
  • 46
  • 1
    It's more accurate to say it creates a new integer object and assigns it to the name `element`. See e.g. http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables – jonrsharpe Jul 11 '14 at 22:54
0

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
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331