Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a number already exist in a list in python

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()?

like image 378
PhoonOne Avatar asked Feb 02 '13 23:02

PhoonOne


People also ask

How do you check if an input is in a list Python?

count() to check if the list contains. Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0. If it returns a positive integer greater than 0, it means the list contains the element.

How do you check if a string contains an element from a list in Python?

The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you check if a list contains any value from another list?

Using any() along with a generator expression: list1 = ['item1','item2','item3'] list2 = ['item4','item5','item3'] if any(x in list1 for x in list2): print("Duplicates found.") else: print("No duplicates found.")

How do you check if an element is not present in a list Python?

In & Not in operators“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.


1 Answers

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 
like image 174
raph.amiard Avatar answered Sep 28 '22 03:09

raph.amiard