How can I overwrite numbers in a list?

Why doesn’t this work?
#Write your function here
def divisible_by_ten(nums):
for num in nums:
if num % 10 == 0:
num = 10
return nums.count(10)

#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))

Hey @6sun, welcome to the forums!

Why are you doing it like this? Why don’t you just use a variable to increment the number of tens?

Here’s why this doesn’t work though:

x = [1,2,3,4,3]
y = x[0]
y = 3

-> [1,2,3,4,3]
-> 3

This is basically what you’re doing. I don’t think it could work.

I know how to use a variable to do it but I still want to know why this doesn’t work.
I was trying to turn [20, 25, 30, 35, 40] into [10, 25, 10, 35, 10] and use .count(10) to count.
What is wrong with it? I still don’t get it.

i think there are two parts to this answer, first, using the for loop like you do:

for num in nums:

now num will hold read-only values of the list, any changes made to num won’t persist

to update elements in a list, use an index:

the_list[index] = 'new value'

as for the second part, i wouldn’t use .count(), you already have a loop, so why not use that to count the number of occurrences?

1 Like