Algorithms & data structures
Classic patterns — search, sort, stacks, queues, and practical complexity-aware code.
How to Flatten List of Dict Values in Python
This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.
def flatten_dict_values(dicts):
flattened = []
for d in dicts:
for value in d.values():
if isinstance(value, list):
flattened.extend(value)
else:
flattened.append(value)
return flattened
if __name__ == "__main__":
data = [
{"a": …
Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
def sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__"…
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.