Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
Check if List is Sorted Ascending in Python
Verify that a list is sorted in ascending order using the all() function and a generator expression.
def is_sorted_ascending(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_lists = [
[1, 2, 3, 4, 5],
[1, 3, 2, 4, 5],
[5, 4, 3, 2, 1],
[1, 1, 2, 2, 3],
[10],
[]
]
for lst in test_lists:
print(f"{l…
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
from collections import Counter
from datetime import datetime, timedelta
# Simulated commit data
commits = [
{"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
{"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
{"author": "Alice", "timestamp": datetime.now() - timedelta…
How to Check if a List is Sorted in Descending Order in Python
This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.
def is_descending(lst):
"""Return True if list is sorted in descending order."""
return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_cases = [
[5, 4, 3, 2, 1],
[3, 3, 2, 1],
[1, 2, 3],
[10, 8, 9],
[]
]
for case in …
How to Compute Percentile Value from Sorted List in Python
Compute any percentile value from a sorted list using linear interpolation between ranks.
def percentile(sorted_data, percentile_value):
"""Return the value below which `percentile_value`% of data falls."""
if not sorted_data:
raise ValueError("Cannot compute percentile of empty list")
if not 0 <= percentile_value <= 100:
raise ValueError("Percentile must be between 0 and 100")
…
How to Find the Median of a List in Python
Compute the median of an unsorted numeric list using the statistics module in Python.
import statistics
def median_of_list(numbers):
return statistics.median(numbers)
if __name__ == "__main__":
sample = [7, 3, 1, 4, 9, 2, 8]
print(median_of_list(sample))
How to Find the Third Smallest Element in a Python List
Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.
def find_third_smallest(numbers):
if len(numbers) < 3:
return None
unique_sorted = sorted(set(numbers))
if len(unique_sorted) < 3:
return None
return unique_sorted[2]
if __name__ == "__main__":
sample = [5, 2, 8, 2, 9, 1, 7, 3]
result = find_third_smallest(sampl…
How to Merge Two Sorted Lists in Python
Merge two sorted lists into one sorted list using a two-pointer loop, then extend with remaining elements.
def merge_sorted_lists(list1, list2):
merged = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
merged.extend(list1[i:])
merged…
How to Partition a List Around a Pivot in Python
This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.
def partition_list(lst, pivot):
less = []
equal = []
greater = []
for item in lst:
if item < pivot:
less.append(item)
elif item == pivot:
equal.append(item)
else:
greater.append(item)
return less + equal + greater
if __name__ == "__main__…
How to Sort a List in Python in Ascending and Descending Order
This code demonstrates three ways to sort a list in Python: returning a new sorted list with sorted(), reversing the sort order, and sorting a list in place with the list.sort() method.
def get_sorted_data(numbers):
"""Return a new list sorted in ascending order."""
return sorted(numbers)
def reverse_sort(data):
"""Return a new list sorted in descending order."""
return sorted(data, reverse=True)
def sort_in_place(data):
"""Sort the given list in place (modifies original)."""
…
How to Sort a List of Dictionaries by a Key in Python
Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.
def sort_dicts_by_key(data, key, reverse=False):
return sorted(data, key=lambda item: item.get(key), reverse=reverse)
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sort_dicts_b…
How to Sort a List of Tuples by the Second Element in Python
Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.
def sort_tuples_by_second(tuples_list):
"""Sort a list of tuples by the second element."""
return sorted(tuples_list, key=lambda x: x[1])
if __name__ == "__main__":
data = [(1, 5), (3, 2), (2, 8), (4, 1)]
sorted_data = sort_tuples_by_second(data)
print("Original list:", data)
print("Sorted by…
Browse by section
Each section groups closely related Python snippets.
Lists & loops — Python code examples
What you will find here
This page collects lists & loops 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.