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()
?
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.
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!")
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.")
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With