check if a number already exist in a list in python

Question:

I am writing a python program where I will be appending numbers into a list, but I don’t want the numbers in the list to repeat. So how do I check if a number is already in the list before I do list.append()?

Asked By: PhoonOne

||

Answers:

If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: –

>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])

If order is a matter of concern, then you can use: –

>>> def addUnique(l, num):
...     if num not in l:
...         l.append(num)
...     
...     return l

You can also find an OrderedSet recipe, which is referred to in Python Documentation

Answered By: Rohit Jain

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Answered By: Keith

You could do

if item not in mylist:
     mylist.append(item)

But you should really use a set, like this :

myset = set()
myset.add(item)

EDIT: If order is important but your list is very big, you should probably use both a list and a set, like so:

mylist = []
myset = set()
for item in ...:
    if item not in myset:
        mylist.append(item)
        myset.add(item)

This way, you get fast lookup for element existence, but you keep your ordering. If you use the naive solution, you will get O(n) performance for the lookup, and that can be bad if your list is big

Or, as @larsman pointed out, you can use OrderedDict to the same effect:

from collections import OrderedDict

mydict = OrderedDict()
for item in ...:
    mydict[item] = True
Answered By: raph.amiard

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order
Answered By: Octipi

To check if a number is in a list one can use the in keyword.

Let’s create a list

exampleList = [1, 2, 3, 4, 5]

Now let’s see if it contains the number 4:

contains = 4 in exampleList

print(contains)
>>>> True

As you want to append when an element is not in a list, the not in can also help

exampleList2 = ["a", "b", "c", "d", "e"]

notcontain = "e" not in exampleList2

print(notcontain)
>>> False

But, as others have mentioned, you may want to consider using a different data structure, more specifically, set. See examples below (Source):

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}

'orange' in basket                 # fast membership testing
True

'crabgrass' in basket
False

# Demonstrate set operations on unique letters from two words
...
a = set('abracadabra')
b = set('alacazam')
a                                  # unique letters in a
>>> {'a', 'r', 'b', 'c', 'd'}

a - b                              # letters in a but not in b
>>> {'r', 'd', 'b'}

a | b                              # letters in a or b or both
>>> {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

a & b                              # letters in both a and b
>>> {'a', 'c'}

a ^ b                              # letters in a or b but not both
>>> {'r', 'd', 'b', 'm', 'z', 'l'}
Answered By: Gonçalo Peres