Python Find in List: Complete Guide

python find in list

Python find in list is a powerful and frequently used technique that allows you to search for a particular element within a list. This can be useful for locating a particular item in a list or finding all items that match certain criteria. Let’s look at different ways to do it in Python.

In this post, we will discuss the below points. If you want to understand a specific point, you can jump over that topic by clicking that.

  1. General
  2. Get List Values
  3. With Function
  4. Other

General

In this section, we will understand how to get some general statistics of a list.

Length of a List

To find the length of a list or size of a list in Python, you can use the len() function. Here’s an example:

# python find list size
my_list = [1, 2, 3, 4, 5]
list_length = len(my_list)
print(list_length)  # Output: 5

Sort a List

To sort a list in Python, you can use the sorted() function.

my_list = [5, 3, 1, 8, 2]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 2, 3, 5, 8]

By default, sorted() function sorts the list in ascending order. You can pass the reverse parameter to sort the list in descending order:

my_list = [5, 3, 1, 8, 2]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)  # Output: [8, 5, 3, 2, 1]

Find largest difference in list

To find the largest difference between any two elements in a list, you can use the following approach:

  1. Sort the list in ascending order
  2. Subtract the first element from the last element
my_list = [5, 3, 1, 8, 2]

# Sort the list
sorted_list = sorted(my_list)

# Subtract the first element from the last element
largest_difference = sorted_list[-1] - sorted_list[0]
print(largest_difference)  # Output: 7

Alternatively, you can also use the max() and min() functions to find the largest difference:

my_list = [5, 3, 1, 8, 2]

# Find the difference between the largest and smallest elements
largest_difference = max(my_list) - min(my_list)
print(largest_difference)  # Output: 7

Find difference between two lists in Python

To find the difference between two lists in Python, you can use the set() function to convert both lists to sets, then use the difference() method to find the elements that are present in one set but not in the other.

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# Find the elements that are present in list1 but not list2
difference = set(list1).difference(set(list2))
print(difference)  # Output: {1, 2}

# Find the elements that are present in list2 but not in list1
difference = set(list2).difference(set(list1))
print(difference)  # Output: {5, 6}

You can also use the symmetric_difference() method to find the elements that are present in one set or the other, but not both:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# Find the elements that are present in one set or the other, but not both (exclude common elements)
difference = set(list1).symmetric_difference(set(list2))
print(difference)  # Output: {1, 2, 5, 6}

Find most frequent element in list

To find the most frequent element in a list in Python, you can use the Counter class from the collections module.

from collections import Counter

my_list = [1, 2, 3, 1, 2, 2, 3, 3, 3]

# Find the frequency of each element
frequency = Counter(my_list)

# Find the most frequent element
most_frequent = frequency.most_common(1)
print(most_frequent)  # Output: [(3, 4)]

The most_common() method returns a list of tuples, where each tuple contains an element and its frequency. In the example above, the most frequent element is 3, which appears 4 times in the list.

Also Read:  Best Udemy Courses to learn Django with Learning Path

You can also pass a parameter to the most_common() method to specify how many of the most frequent elements you want to get. For example, to get the two most frequent elements, you can do:

from collections import Counter

my_list = [1, 2, 3, 1, 2, 2, 3, 3, 3]

# Find the frequency of each element
frequency = Counter(my_list)

# Find the two most frequent elements
most_frequent = frequency.most_common(2)
print(most_frequent)  # Output: [(3, 4), (2, 3)]

Get List Value

To get the values of a list in Python, we can use indexing or slicing. Here’s an example using indexing.

Get First value of a List

my_list = [1, 2, 3, 4, 5]

# Get the first value
first_value = my_list[0]
print(first_value)  # Output: 1

Get last element of a list

# Get the last value
last_value = my_list[-1]
print(last_value)  # Output: 5

Below are the examples using slicing.

Get first n values

my_list = [1, 2, 3, 4, 5]

# Get the first three values
first_three_values = my_list[:3]
print(first_three_values)  # Output: [1, 2, 3]

Get last n values

# Get the last three values
last_three_values = my_list[-3:]
print(last_three_values)  # Output: [3, 4, 5]

Find middle three values

# Get the middle three values
middle_three_values = my_list[1:-1]
print(middle_three_values)  # Output: [2, 3, 4]

Find and return index of a list element

To find the index of a list element in Python, you can use the list.index() method.

my_list = [1, 2, 3, 4, 5]
index = my_list.index(3)
print(index)  # Output: 2

The list.index() method returns the index of the element from the list. If the element is not found, it raises an ValueError exception. To avoid this error you can use an if statement.

Find in list with regex

To find an element in a list that matches a certain pattern in Python, you can use the re module to compile a regular expression. Then use the re.search() function to find the element.

import re

my_list = ["apple", "banana", "cherry", "date"]
pattern = re.compile("^b.*")  # Match elements that start with "b"

for element in my_list:
    if pattern.search(element):
        print(element)  # Output: "banana"

With Function

Find in list with function

To find an element in a list using a function in Python, you can use the filter() function.

def is_even(x):
    return x % 2 == 0

my_list = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, my_list)
print(list(even_numbers))  # Output: [2, 4]

The filter() function applies the function to each element of the list and returns a list of elements for which the function returns True.

You can also use a list comprehension technique to achieve the same result:

def is_even(x):
    return x % 2 == 0

my_list = [1, 2, 3, 4, 5]
even_numbers = [x for x in my_list if is_even(x)]
print(even_numbers)  # Output: [2, 4]

Alternatively, you can use the any() function to check if any element in the list satisfies a condition:

def is_even(x):
    return x % 2 == 0

my_list = [1, 2, 3, 4, 5]
if any(is_even(x) for x in my_list):
    print("There is at least one even number in the list")
else:
    print("There are no even numbers in the list")
Output:
There is at least one even number in the list

Find in list with lambda function

You can replace the normal function with a lambda function to reduce the code length. Let’s see how.

my_list = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, my_list)
print(list(even_numbers))  # Output: [2, 4]

Other

Let’s list down the rest of the common python find in list techniques.

Also Read:  Automatic Update Google Sheet from Python

Find in list by value

There are several ways to find an element in a list by value in Python. One of the popular techniques is in operator.

my_list = [1, 2, 3, 4, 5]
if 2 in my_list:
    print("2 is in the list")
else:
    print("2 is not in the list")
Output: 
2 is in the list

Search and find in list of tuples

To search and find an element in a list of tuples in Python, you can use a for loop and check if the element you’re looking for is present in any of the tuples.

my_list = [("apple", "red"), ("banana", "yellow"), ("cherry", "red")]
for element in my_list:
    if element[0] == "banana":
        print("banana is in the list")
        break
else:
    print("banana is not in the list")
Output:
banana is in the list

Find in list of objects by attribute

To find an element in a list of objects by attribute in Python, you can use a for loop and check if the attribute of the object you’re looking for is equal to the value you’re searching for.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people = [Person("Alice", 20), Person("Bob", 30), Person("Charlie", 25)]
for person in people:
    if person.name == "Bob":
        print("Bob is in the list")
        break
else:
    print("Bob is not in the list")
Output:
Bob is in the list

Find in list and replace

To find an element in a list and replace it with a new element in Python, you can use a for loop to find the index of the element and use the list.insert() and list.pop() methods to replace it.

my_list = [1, 2, 3, 4, 5]
for i, element in enumerate(my_list):
    if element == 3:
        my_list.pop(i)
        # Replace 3 with 10
        my_list.insert(i, 10)
        break
print(my_list)  # Output: [1, 2, 10, 4, 5]

You can also use the map() function to achieve the same result:

my_list = [1, 2, 3, 4, 5]
def replace(x):
    if x == 3:
        return 10
    return x
modified_list = list(map(replace, my_list))
print(modified_list)  # Output: [1, 2, 10, 4, 5]

Find strings in list

To find strings in a list in Python, you can use a for loop to iterate over the elements and check if each element is a string.

my_list = ["apple", "banana", "cherry", 123, 456]
for element in my_list:
    if isinstance(element, str):
        print(element)
apple
banana
cherry

Get list keys

Note that a list in Python does not have keys like a dictionary does. The elements in a list are accessed by their index, which is a numerical position in the list.

Also Read:  How to send SMS using Python

Find zeros in list

To find zeros in a list in Python, you can use a for loop to iterate over the elements and check if each element is equal to zero.

my_list = [1, 0, 2, 3, 0, 4, 5]
for element in my_list:
    if element == 0:
        print(element)
Output:
0
0

Find duplicates in list

To find duplicates in a list in Python, you can use a for loop and a set to check which elements have already been seen.

my_list = [1, 2, 3, 1, 2, 3, 4, 5]
duplicates = []
seen = set()
for element in my_list:
    if element in seen:
        duplicates.append(element)
    else:
        seen.add(element)
print(duplicates)  # Output: [1, 2, 3]

Alternatively, we can use a Counter from the collections module to count the occurrences of each element and find the elements that have a count greater than 1.

from collections import Counter

my_list = [1, 2, 3, 1, 2, 3, 4, 5]
counter = Counter(my_list)
duplicates = [element for element, count in counter.items() if count > 1]
print(duplicates)  # Output: [1, 2, 3]

Find index of NumPy array in list

Sometimes a NumPy array itself can be inside a list. In order to find the index of a NumPy array in a list in Python, we can use a for loop and the enumerate() function to iterate over the elements and their indexes to check if the element is equal to the NumPy array:

import numpy as np

my_list = [1, 2, 3, np.array([4, 5, 6]), 7, 8]
for i, element in enumerate(my_list):
    if (element == np.array([4, 5, 6])).all():
        print(i)  # Output: 3
        break

End Note

That’s it! In this tutorial, I have listed down some popular techniques to find in list methods that we are using day to day doing Python programming.

I hope you find this article helpful. If you have any questions or suggestions regarding this article, please let me know in the comment section below. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python.

Leave a comment