Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
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 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}")
…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.