Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Enumerate a Python List with a Custom Start Index
Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=5):
print(f"{index}: {fruit}")
Find All Occurrences of an Item in a Python List
Loop through a list with enumerate() to collect the index of every match for a target value.
def find_all(data, target):
"""Return indices of every occurrence of target in a list."""
indices = []
for index, item in enumerate(data):
if item == target:
indices.append(index)
return indices
if __name__ == "__main__":
sample = [10, 20, 30, 20, 40, 20, 50]
target_value …
Format Lists of Tuples into Numbered Lines in Python
This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.
def format_students(students):
formatted = []
for i, student in enumerate(students, start=1):
name, grade = student
formatted.append(f"{i}. {name}: {grade}")
return "\n".join(formatted)
if __name__ == "__main__":
students = [
("Alice", 92),
("Bob", 85),
("Charl…
How to Process Text Lines with Lists and Loops in Python
This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.
def process_text(lines):
"""Convert a list of text lines to uppercase and report line statistics."""
processed = []
total_chars = 0
for index, line in enumerate(lines, start=1):
cleaned = line.strip().upper()
processed.append(cleaned)
total_chars += len(cleaned)
pri…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
How to Process Text with Lists and Loops in Python
Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.
# text_processor.py
def process_text(lines):
"""Count words, show uppercase, and count characters per line."""
total_words = 0
print("Line-by-line analysis:")
for i, line in enumerate(lines, start=1):
words = line.split()
total_words += len(words)
print(f" Line {i}: {len(words…
How to check list items by type and emptiness in Python
Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.
def check_data(data):
"""Check each item in a list and print whether it's valid."""
for i, item in enumerate(data):
if item is None or item == "":
status = "empty"
elif isinstance(item, (int, float)):
status = "number"
else:
status = "text"
pr…
How to Read a Text File Line by Line in Python
Reads a text file line by line with an enumerated for loop and prints each line number and content.
from pathlib import Path
def read_lines(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
for line_number, line in enumerate(file, start=1):
print(f"Line {line_number}: {line.rstrip()}")
if __name__ == "__main__":
sample_file = Path("sample.txt")
sample_file.write_text(…
Find All Indices of a Target Value in a Python List
Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.
def find_all_indices(arr, target):
return [i for i, value in enumerate(arr) if value == target]
if __name__ == "__main__":
sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
target = 2
result = find_all_indices(sample_list, target)
print(result)
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…
Enumerate a Generator With a Running Total in Python
A generator that yields each element with its index and a cumulative sum, letting you track a running total as you iterate.
def running_total_enum(iterable):
"""Yields (index, item, running_total) for each element."""
total = 0
for index, item in enumerate(iterable):
total += item
yield index, item, total
if __name__ == "__main__":
numbers = [10, 20, 30, 40, 50]
for idx, value, running_sum in running_to…
How to Create a Line-Numbered Generator with enumerate start in Python
This Python code defines a generator that yields lines prefixed with their index, using enumerate's start parameter to offset numbering.
def line_numbered_lines(lines, start=1):
for idx, line in enumerate(lines, start):
yield f"{idx:3} {line}"
if __name__ == "__main__":
sample = ["first line", "second", "third"]
for numbered in line_numbered_lines(sample, start=10):
print(numbered)
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.