Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Condition for list item Python

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading