Lists and Functions 15/18

In the code below, I am trying to multiply each number in the list by 2, and print out the new list. However, it just prints the original list. What is wrong with this code, and how should I modify it? Thanks!

def list_function(n):
    for i in n:
        i = i * 2
    return n

x = [4,5,8]
print (list_function(x))

which new list? There is no new list? i contains read only values from the list, any changes made to it won’t persist and you neither update the existing list (n) or create a new list


Thanks but how can I put multiply each item in the list by 2 and then print that list?

I’ve also tried the code below and it won’t work.

n = [4,5,8]
for i in range(len(n)):
    i = i * 2
    print n[i]

where did the function go?

to update an element in a list we need to do:

your_list[index] = "new value"

now, index can also be a variable.


I just figured out a code that works based on your reply:

n = [4,5,8]
for i in range(len(n)):
    n[i] = n[i] * 2
print (n)

Thanks a lot!

good, that was my intention. I hope you learned more now then i would just have given you the solution :slight_smile: