Skip to content

Python find element in list by condition

  • by

You can use for loop with an if-else statement to find elements in a list by the condition in Python. The else part to a for-loop and this else part will be executed if the loop finishes “normally”, without calling a break.

for animal in animals:
    if len(animal) > 5:
        first = animal
        break
else:
    first = None

Using filter and next

first = next(filter(lambda animal: len(animal) > 5, animals), None)

Python finds an element in a list by condition example

A simple example code gets the first item from an iterable that matches a condition.

lista = [1, 2, 3, 1, 2, 3]

res = None

for index, value in enumerate(lista):
if value == 2:
res = value
break
print(res)

Get the index of the first element in the List that matches a condition.

lista = [1, 2, 3, 1, 2, 3]

firstIndex = -1

for index, value in enumerate(lista):
if value < 1:
firstIndex = index
break
print(firstIndex)

Another example

animals = ['snake', 'camel', 'etruscan shrew', 'ant', 'hippopotamus', 'giraffe']

for animal in animals:
if len(animal) > 5:
first = animal
break
else:
first = None
print(first)

Output:

Python find element in list by condition

Finding the index of elements based on a condition using Python list comprehension.

a = [1, 2, 3, 1, 2, 3]

res = [i for i in range(len(a)) if a[i] > 2]

print(res)

Output: [2, 5]

How to check if all elements of a list match a condition?

Answer: If you want to check if any item in the list violates a condition use all() function:

lista = [1, 2, 3, 1, 2, 3]

res = all(ele > 3 for ele in lista)

print(res) #flase

To remove all elements not matching, use filter

# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *