Nanu
Nanu

Reputation: 3

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]

Upvotes: 0

Views: 469

Answers (2)

Leonardo Reina
Leonardo Reina

Reputation: 11

The list is not updating because you never call your function. You should call your function at least once to add the number "4".

If you really need to return a boolean, you can do like so:

    number = 4
    number_list = [2, 3, 5]
    
    
    def check_number_in_list(number, number_list):
        if number in number_list:
            number_list.append(i)
            return True
        return False
    
    check_number_in_list(number, number_list)
    print(number_list)

Upvotes: 0

Park
Park

Reputation: 2484

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]

Upvotes: 1

Related Questions