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()?
I am writing a python program where I will be appending numbers into a
Share
You could do
But you should really use a set, like this :
EDIT: If order is important but your list is very big, you should probably use both a list and a set, like so:
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: