Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Linear search

Inspect values in encounter order until the first equality match.

Version: Python 3.14; repository image, production runtime not attested

Syntax

next((i for i, value in enumerate(values) if value == target), None)

Inspect values in encounter order until the first equality match.

The best case needs one comparison on a nonempty input and an absent target requires a full scan, so worst-case comparisons grow linearly. Returning None for absence keeps a valid index zero distinct.

When the source is an iterator a successful search leaves its remaining tail available.

Examples

def locate(values, target):
    checks = 0
    for i, value in enumerate(values):
        checks += 1
        if value == target:
            return i, checks
    return None, checks
stream = iter(["A", "B", "A"])
print(locate(stream, "A"), list(stream))
print(locate(["A", "B"], "Z"), locate([], "Z"))

Result

(0, 1) ['B', 'A']
(None, 2) (None, 0)

When the source is an iterator a successful search leaves its remaining tail available.

Sources