0

I have a list ['1', '2', '3', '4'] and I want to convert it to the following: ['1.0', '2.0', '3.0', '4.0']. In the code below, why does the second attempt work and not the first?

>>> list = ['1', '2', '3', '4']
>>> for element in list:
...     element = element + '.0'
...
>>> print(list)
['1', '2', '3', '4']
>>> for element in range(len(list)):
...     list[element] = list[element] + '.0'
...
>>> print(list)
['1.0', '2.0', '3.0', '4.0']
3
  • 1
    Don't use list as variable name. Commented Nov 4, 2014 at 11:35
  • 1
    how could have first attempt worked, you are modifying each element not each list element Commented Nov 4, 2014 at 11:36
  • Woops, forgot about that, thanks Commented Nov 4, 2014 at 11:36

3 Answers 3

2

element is the local variable and assigned only to the current element of list.

In the second case list[element] is assigned to list in which element points to the current index of list.

Sign up to request clarification or add additional context in comments.

Comments

0

You are not updating the list. You merely update the element variable.

Comments

0
new_list = [x + '.0' for x in old_list]

7 Comments

That's an answer, but not to the question asked.
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
regardless of not being an answer, thanks, that's really helpful
@Philio This is very much an answer, and not a comment. You downvote a bad answer, not delete it.
@Korem you said that it was not an answer to the question asked? Hence I flagged it from review as not answering the right question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.