I’m trying to check the condition of the list items.
If any item is less than 100, it shall be 100.
value = [50, 100, 200, 300, 400]
for item in value:
if item < 100:
item = 100
But it does not work as I hope.
My desired outcome is value = [100, 100, 200, 300, 400]
>Solution :
The other answers are correct that you can use list comprehension if you understand it, and it’s a great thing to learn as well. However if you’re looking for a more traditional for loop to accomplish that here you go!
for i in range(len(value)):
if value[i] < 100:
value[i] = 100
The mistake that you’re making with your code is that item is not an element in your list, it’s a copy of the element in the list. So when you change it, you’re just changing that copy which is deleted at the end of each loop. In my version we are instead iterating through a list of numbers, each one corresponding to a position in the list. Then we access each list element directly using this address in order to change it. Hope this helps! Have a great one!