How to Check if an Element exists in List in Python

share link

by vsasikalabe dot icon Updated: Jan 31, 2023

technology logo
technology logo

Guide Kit Guide Kit  

Checking if an element already exists in a list is often used in various programming situations, such as:  

  • Data Validation: Ensure duplicate data is not entered into a list.  
  • Searching: Quickly check if an element is present in a list without iterating through the entire list.  
  • Algorithm optimization: In some algorithms, it's important to know if an element already exists in a list so that you can take appropriate action.  
  • Set operations: When working with sets, checking for the presence of an element in a list is a fundamental operation.  


In Python, you can check if an element exists in a list using the "in" keyword.  

  • in: The "in" keyword is used in Python to check if a value is present in a collection of values, such as a list, tuple, or dictionary.  

Alternatively, you can use the "any()" or "all()" function in python to check if the element present in the list or not.  

  • any() or all(): The any() function in Python is used to check if any element in an iterable (such as a list, tuple, or dictionary) is true.  


You may have a look at the code given below to know more about the topic. 

Fig : Preview of the output that you will get on running this code from your IDE.

Code

class Movie:
    def __init__(self, name, pegi, year):
        self.name = name
        self.pegi = pegi
        self.year = year

    def __eq__(self, other): 
        if not isinstance(other, Movie):
            # don't attempt to compare against unrelated types
            return NotImplemented

        return self.name == other.name # and self.year == other.year
    
    def __hash__(self):
        return hash(self.name)
        # if you want to compare with year too.
        # return hash(self.name + str(self.year))   
      
    def __str__(self):
        # This is how each movie will be printed. 
        # You can improve the formatting here.
        return "Movie name: {}, Year: {}".format(self.name, self.year)

class Movies(): # it makes no sense that Movies should inherit Movie, don't do that.

    def __init__(self):
        self.collection = set()

    def addMovieToCollection(self, name, pegi, year):
        current_movie = Movie(name, pegi, year)
        if current_movie in self.collection:
            print("That movie like" + current_movie.name + " already exists")
        else:
            self.collection.add(current_movie)
            print("Added " + current_movie.name + " " + str(current_movie.year))
            
    def __str__(self):
        # Join the collection together how you would like to represent it.
        response = "\nMovies Collection:\n"
        for movie in self.collection:
            response += str(movie) + "\n"
        return response

f = Movies()

f.addMovieToCollection("Iron Man 1", "blue sign", 1995)
f.addMovieToCollection("Iron Man 2", "+7", 1995)
f.addMovieToCollection("Iron Man 1", "blue sign", 1996)
f.addMovieToCollection("Iron Man 1", "blue sign", 1995)
print(f)

Added Iron Man 1 1995
Added Iron Man 2 1995
That movie likeIron Man 1 already exists
That movie likeIron Man 1 already exists

Movies Collection:
Movie name: Iron Man 2, Year: 1995
Movie name: Iron Man 1, Year: 1995
Iron Man 11995

Instructions

Follow the steps carefully to get the output easily.

  1. Download and Install the PyCharm Community Edition on your computer.
  2. Create new python file on your IDE.
  3. Copy the snippet using the 'copy' button and paste it in your python file.
  4. Run the current file to generate the output.


I hope you found this useful.


I found this code snippet by searching for ' Checking already exists element in list using Python'in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in PyCharm 2021.3.
  2. The solution is tested on Python 3.9.7.


Using this solution, we are able to Check already exists element in list using Python with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to Check already exists element in list using Python.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page