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

How to add an item in a list with .append in a conditional loop?

It should be easy, but i can’t:

If the number is in the list return True but if not add the number to the list.

i=4
list=[2,3,5]
def check(i,list):
    if i in list:
        return True
    else:
        return list.append(i)
print (list)

#The result that I want: [2,3,5,4]

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

#The result that I have: {2,3,5]

>Solution :

You did not call the function, so I added a line calling the function right before the print. I also changed a code to make the function simpler.

More importantly, you should avoid to use pre-defined keyword such as list (see https://www.programiz.com/python-programming/keyword-list). I changed the variable name to l, instead of list.

i = 4
l = [2, 3, 5]


def check(i, l):
    if i not in l:
        #return l.append(i) # It works, but you do not need to return the list.
        l.append(i) # It also works.

check(i, l)
print(l)
# [2, 3, 5, 4]
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