-2

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]

Alphatio
  • 47
  • 5

4 Answers4

4

you can use list comprehension as below:

pattern:
[f(x) if condition else g(x) for x in sequence]
value = [100 if item < 100 else item for item in value]

take a look at this link if/else in a list comprehension

Khanzadeh_AH
  • 139
  • 6
1

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!

AdamEshem
  • 129
  • 6
  • I guess this is the way if I do not use list comprehension to solve it. This is clearer than list comprehension in some cases. – Alphatio Apr 13 '22 at 06:33
1

Accessing values in a list with an index is slow. So we would like to avoid the traditional but unpythonic approach with for i in range(len(value)):. enumerate gives us the index and the value and now we need to use the index only when we want to write back to the list.

for i, number in enumerate(value):
    if number < 100:
        value[i] = 100
Timus
  • 10,974
  • 5
  • 14
  • 28
Matthias
  • 12,873
  • 6
  • 42
  • 48
0

You are just updating item, not the actual elements of value. Additionally, try using list comprehension:

value = [v if v > 100 else 100 for v in value]