Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
How to Sort a List of Dictionaries by Key with a Lambda in Python
Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.
def get_students():
return [
{"name": "alice", "score": 85},
{"name": "bob", "score": 92},
{"name": "carol", "score": 78},
{"name": "dave", "score": 92},
]
students = get_students()
sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
How to Sort a List of Numbers in Python with Default Parameters
Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.
def sort_numbers(numbers, reverse=False):
"""Sort a list of numbers in ascending or descending order."""
return sorted(numbers, reverse=reverse)
def main():
numbers = [5, 2, 9, 1, 7, 3]
# Default sort (ascending)
ascending = sort_numbers(numbers)
print(f"Ascending: {ascending}")
…
How to Use Lambda Sorting Keys in Python
Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.
# Demonstrate lambda as a sorting key function
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 75},
{"name": "Diana", "grade": 95}
]
# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
How to Use a Lambda Sort Key in Python
Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.
def sort_words(words):
"""Sort words by length, then alphabetically using a lambda key."""
return sorted(words, key=lambda word: (len(word), word))
if __name__ == "__main__":
sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
result = sort_words(sample_words)
print("Original:", sampl…
How to Use a Lambda Sorting Key in Python
Sort a list of strings by their last letter using a lambda function as the sorting key.
def get_last_letter(word):
return word[-1]
words = ["banana", "apple", "cherry", "date", "elderberry"]
if __name__ == "__main__":
sorted_words = sorted(words, key=get_last_letter)
print(sorted_words)
How to implement binary search in Python
Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ ==…
Profile Python functions with cProfile
Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.
import cProfile
import pstats
import io
def slow_function():
total = 0
for i in range(100000):
total += i ** 2
return total
def medium_function():
return sum(range(10000))
def fast_function():
return sum(range(100))
def main():
result1 = slow_function()
result2 = medium_func…
Sort a List of Dictionaries by Key in Python
Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.
def get_items():
return [
{"name": "apple", "price": 3},
{"name": "banana", "price": 1},
{"name": "cherry", "price": 2},
]
if __name__ == "__main__":
items = get_items()
sorted_items = sorted(items, key=lambda item: item["price"])
for item in sorted_items:
print(f"{…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics 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.