Appending an id to a list if not already present in a string

I am trying to check if id is in a list and append the id only if its not in the list using the below code..however I see that the id is getting appended even though id is already present in the list.. can anyone provide inputs on what is wrong here?

   list = ['350882 348521 350166\r\n']
    id = 348521
    if id not in list:
        list.append(id)
    print list

OUTPUT:-
['350882 348521 350166\r\n', 348521]

Solution 1:

What you are trying to do can almost certainly be achieved with a set.

>>> x = set([1,2,3])
>>> x.add(2)
>>> x
set([1, 2, 3])
>>> x.add(4)
>>> x.add(4)
>>> x
set([1, 2, 3, 4])
>>> 

using a set's add method you can build your unique set of ids very quickly. Or if you already have a list

unique_ids = set(id_list)

as for getting your inputs in numeric form you can do something like

>>> ids = [int(n) for n in '350882 348521 350166\r\n'.split()]
>>> ids
[350882, 348521, 350166]

Solution 2:

A more pythonic way, without using set is as follows:

lst = [1, 2, 3, 4]
lst.append(3) if 3 not in lst else lst