This tutorial will discuss about unique ways to add element to list if not already present in List.
Table Of Contents
Introduction to not in
Operator in Python
In Python, we have an operator not in
, that we can apply on an element and a sequence. Like this,
Let’s see the complete example,
element not in sequence
If checks for the existance of element in the given sequence, and returns True
if the given element does not exist in the sequence. Whereas, it returns False
if the given element is present in the given sequence. This sequence can be a list
, set
, tuple
or any other iterable sequence in Python.
Frequently Asked:
Using ‘not in’ Operator to append element if not already present in Python List
To check if an element is present in a list or not, we can apply the not in
operator on the element and the list. If it returns True
, then it means element is present in the list, otherwise element is not present in the list. So, if given element is not present in list, then append it to the list using the append()
function.
This approach is usefull, if we want to keep only unique elements in a list, just like a set.
Example 1
In this example, we have a list of strings, and we will add a new string (‘the’) in it. But before that, we will check if the given string exists in the list or not, and if it is not present in the list, then only we will add the element to it.
Let’s see the complete example,
Latest Python - Video Tutorial
listOfStrings = ['is', 'are', 'at', 'why', 'what'] # Element to be added value = 'the' # Add item to list if not already present in list if value not in listOfStrings: listOfStrings.append(value) print(listOfStrings)
Output
['is', 'are', 'at', 'why', 'what', 'the']
As the string ‘the’ was not already present in the list, therefore it got added in list.
Example 2
In this example, we have a list of strings, and we will try to add a new string (‘at’) in it, but if and only if it is not already present in the list.
Let’s see the complete example,
listOfStrings = ['is', 'are', 'at', 'why', 'what'] # Element to be added value = 'at' # Add item to list if not already present in list if value not in listOfStrings: listOfStrings.append(value) print(listOfStrings)
Output
['is', 'are', 'at', 'why', 'what']
As the string at
was already present in the list, therefore it skipped adding it again in the list.
Summary
We learned about a unique to add an element to list if not already present in List. Thanks.
Latest Video Tutorials