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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With