Quick Overview
in scans a list front to back, so membership costs O(n). On a set the identical expression becomes a hash lookup at O(1): same syntax, very different work.
Create a function check(lst, el) that checks if a list lst contains an element el. Return True if present, otherwise False.
Searching for items in lists is a daily requirement in permission checking, tag filtering, and lookup validation.
Use Python's built-in in membership operator:
def check(lst, el):
return el in lst
# Testing our function
print(check([1, 2, 3, 4, 5], 3)) # Output: True
print(check([1, 1, 2, 1, 1], 3)) # Output: False
print(check(["a", "b", "c"], "b")) # Output: True
print(check([], 5)) # Output: False
in Operator WorksFor lists, the in operator performs a linear search in O(N) time, scanning elements sequentially until a match is found. For O(1) instant lookups on large datasets, use a Python set().
for item in lst: if item == el: return True is unnecessary! Python's in operator does this natively in 1 clean line.Use in for membership checks. Next, let's reverse a list in Python!
A function with no return hands back None, so a forgotten one surfaces as a TypeError at the call site rather than at the line that actually caused it.
minutes * 60 returns an int when given an int, while / always produces a float regardless of the operands. Multiplication preserves the type; division does not.
base * height / 2 always yields a float in Python 3 because / never returns an int, even for whole numbers. // floors instead, which is almost never what an area wants.