Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need clarification with my for loop logic in Python

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?

like image 988
Anantha RamaKrishnan Avatar asked Dec 15 '25 00:12

Anantha RamaKrishnan


1 Answers

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)
like image 99
Hackaholic Avatar answered Dec 16 '25 15:12

Hackaholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!