3

The output should have been [2, 18, 6, 16, 10, 14].

my_list = [1, 9, 3, 8, 5, 7]

for number in my_list:
    number = 2 * number

print my_list     

The problem is that it prints the same my_list values. The logic number = 2 * number isn't even executed?

5 Answers 5

3

you are not updating the list, you are just updating the number variable:

for number in my_list:
    number = 2 * number

There are may way to do this:

Using enumerate:

my_list = [1, 9, 3, 8, 5, 7]

for index,number in enumerate(my_list):
    my_list[index] = 2 * number

print my_list     

Using list comprehension:

my_list = [2*x for x in my_list]

Using Lambda and map:

my_list = map(lambda x: 2*x, my_list)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this quickly in a list comprehension:

my_list = [1,9,3,8,5,7]
new_list = [2*x for x in my_list]

The problem with your code is that when you are looping through my_list, number is not the variable in the list; it is just the value of the that variable. Therefore, changing that value does not change the original variable.

Comments

0

The way this is written will not modify the list in-place. You want something like a list comprehension that you can assign back into my_list.

my_list = [number * 2 for number in my_list]

Comments

0

You have to assign the value back to the item in the list

my_list = [1,9,3,8,5,7]

for i, number in enumerate(my_list):
    my_list[i] = 2 * number

Comments

0

The issue is that you are updating number not my_list. List comprehension is preferable, but here's an explicit way of doing the same thing that highlights where your problem is:

my_list = [1,9,3,8,5,7]
i=0

for number in my_list:
    # Your code here
    my_list[i]=2*number
    i += 1
print my_list

Good luck!

Comments

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.