Anantha RamaKrishnan
Anantha RamaKrishnan

Reputation: 89

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?

Upvotes: 3

Views: 65

Answers (5)

Hackaholic
Hackaholic

Reputation: 19733

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)

Upvotes: 3

Gi0rgi0s
Gi0rgi0s

Reputation: 1867

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!

Upvotes: 0

Patrick Carroll
Patrick Carroll

Reputation: 71

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

Upvotes: 0

Dan Lowe
Dan Lowe

Reputation: 56518

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]

Upvotes: 0

AMACB
AMACB

Reputation: 1298

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.

Upvotes: 1

Related Questions