Skip to content

Python find object in list | Example code

  • by

Python finds the object in the given list that has an attribute (or method result – whatever) equal to the value.

Example Python finds an object in the list

Simple example code.

The naive loop-break on the match. This will assign None to x if you don’t break out of the loop.

import random


class Test:
    def __init__(self, value):
        self.value = value


value = 5

test_list = [Test(random.randint(0, 100)) for x in range(300)]


def find(val):
    for x in test_list:
        if x.value == val:
            print("Found it!")
            break
        else:
            x = None
    return


find(value)

Output:

Python find object in list

Source: stackoverflow.com

Another example single-expression form

This gets the first item from the list that matches the condition, and returns None if no item matches.

class ProjectFile:
    def __init__(self, filename: str,
                 number_of_lines: int,
                 language: str,
                 repo: str,
                 size: int):
        self.filename = filename
        self.number_of_lines = number_of_lines
        self.language = language
        self.repo = repo
        self.size = size


projects = [
    ProjectFile(
        filename="test1.txt",
        number_of_lines=1,
        language="English",
        repo="repo1",
        size=1,
    ),
    ProjectFile(
        filename="test2.txt",
        number_of_lines=2,
        language="German",
        repo="repo2",
        size=2
    ),
]

val = 3
res = next((x for x in projects if x.size == 3), None)

print(res)

Output: None

Do comment if you have any doubts or suggestions on this Python object code.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading