How to add an item in a list with .append conditionally in a 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]

The result that I have: [2,3,5]


Solution 1:

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]