You have a list, and you want to check whether an element you have is already present inside the list. There are a few ways you can do it in Python.
A quick way to check if an item is inside a list
- Create a variable with the value you want to check.
1 |
myvar = 'just' |
- Create a list of items.
1 |
mylist = ['This', 'is', 'just', 'a', 'text', 'string'] |
- Use the IF condition to check the value.
1 |
if myvar in mylist: |
- Use ELSE to execute a message if the value is not present in the list.
The full example is going to look like this:
1 2 3 4 5 6 7 |
mylist = ['This', 'is', 'just', 'a', 'text', 'string'] myvar = 'just' if myvar in mylist: print('The value exists.') else: print('The value does not exist.') |
Alternative version with the list.count() function
If you want to check not only whether the value exists in a list, but also how many times, you can use the list.count function.
1 2 3 4 5 6 7 |
mylist = ['This', 'is', 'just', 'a', 'text', 'string', 'just'] myvar = 'just' if mylist.count(myvar) > 0: print('The number of values inside the list: ' + str(mylist.count(myvar))) else: print('The value does not exist.') |
Add value if unique in a list
In the next example, we are going to create a function that checks whether the value is not present inside a list.
If the value is present, then it means that the value is not unique and the function returns False, otherwise the value is unique, and the function adds it to the list and returns True.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def add_unique(list, value): for element in list: if value in element: return False list.append(value) return True mylist = ['This', 'is', 'just', 'a', 'text', 'string'] add_unique(mylist, ',') add_unique(mylist, 'string') add_unique(mylist, 'right') |