Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
Drop Elements From Start While Condition Is True in Python
This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.
def drop_while(predicate, iterable):
"""Drop elements from the start while predicate is true."""
it = iter(iterable)
for item in it:
if not predicate(item):
yield item
break
yield from it
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 1, 2, 5]
result = list(d…
Find the First Index Where a Condition Is True in Python
Search any iterable for the first element matching a predicate and return its index, or -1 if none match.
def first_true_index(items, condition):
"""Return the first index where condition(item) is True, or -1 if none match."""
for i, item in enumerate(items):
if condition(item):
return i
return -1
if __name__ == "__main__":
numbers = [1, 3, 5, 8, 10, 12]
# Find first number greate…
Find the Last Index Where a Condition Is True in Python
This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.
def last_index_where(sequence, condition):
"""Return the index of the last element in sequence that satisfies condition."""
for i in range(len(sequence) - 1, -1, -1):
if condition(sequence[i]):
return i
return -1
if __name__ == "__main__":
numbers = [1, 4, 7, 2, 9, 5, 8, 3]
is_…
Browse by section
Each section groups closely related Python snippets.
Algorithms & data structures — Python code examples
What you will find here
This page collects algorithms & data structures snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.