Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Process Lines of Text in Python
Strip whitespace, split a multi-line string, count words per line, and print structured summaries using basic string methods and loops.
text = """ Python is great!
Coding is fun.
Python skills help you grow. """
lines = text.strip().splitlines()
line_count = len(lines)
processed = []
for line in lines:
stripped = line.strip()
word_count = len(stripped.split())
processed.append({
"original": line,
"stripped": stripp…
Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
def compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second…
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}")
Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
def extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a…
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…
Generate Data Helper for Beginners in Python
Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.
from random import randint
def build_dataset(size: int, max_val: int) -> list[int]:
data = []
for _ in range(size):
data.append(randint(1, max_val))
return data
def summarize(data: list[int]) -> dict[str, float]:
total = 0
maximum = data[0]
minimum = data[0]
for value in data:
…
How to Build a Text Processor with Lists and Loops in Python
A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.
def process_text(text):
"""Simple text processor for beginners using lists and loops."""
sentences = text.replace('!', '.').replace('?', '.').split('.')
words = text.split()
word_counts = []
for sentence in sentences:
sentence_word_count = len(sentence.split())
word_counts.appe…
How to Calculate a Cumulative Sum in Python
Build a new list where each element equals the running total of all numbers up to that index in the original list.
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0
for num in numbers:
running_total += num
cumulative_sum.append(running_total)
print(cumulative_sum)
How to Convert Data Types in Python Lists
Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.
def convert_data(data):
"""Convert a mixed list of values to strings, ints, and floats."""
result = []
for item in data:
if isinstance(item, (int, float)):
result.append(str(item))
elif isinstance(item, str):
try:
if '.' in item:
r…
How to Count Occurrences of a Value in a Python List
Counts how many times a specific value appears in a list using a simple loop and a counter variable.
def count_occurrences(data, target):
count = 0
for item in data:
if item == target:
count += 1
return count
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
target_value = 5
result = count_occurrences(numbers, target_value)
print(f"The value {targ…
How to Count, Double, and Find Max in a Python List
Three beginner-friendly Python functions that count even numbers, double each value, and find the maximum in a list using simple loops.
def count_even_numbers(numbers):
"""Return the count of even numbers in a list."""
count = 0
for num in numbers:
if num % 2 == 0:
count += 1
return count
def double_values(numbers):
"""Return a new list with each value doubled."""
doubled = []
for num in numbers:
…
How to Filter Even Numbers and Square Them in Python
Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.
def get_even_numbers(numbers):
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
return evens
def get_squares(numbers):
squares = []
for num in numbers:
squares.append(num ** 2)
return squares
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers …
How to Find Local Maxima in a Python List
Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.
def find_peaks(numbers):
"""
Return the indices of local maxima in a numeric list.
A local maximum is an element greater than both its neighbors.
"""
if len(numbers) < 3:
return []
peaks = []
for i in range(1, len(numbers) - 1):
if numbers[i] > numbers[i - 1] and number…
How to Loop Through Lists in Python for Beginners
Transform, filter, sum, and find the maximum in a Python list using basic for loops and conditionals.
def transform_data(numbers):
"""Basic transformation examples using lists and loops."""
doubled = []
for n in numbers:
doubled.append(n * 2)
return doubled
def filter_even(numbers):
"""Keep only even numbers using a loop and condition."""
evens = []
for n in numbers:
if n …
How to Merge Two Lists in Python
Merge two Python lists into a single combined list by appending each element with a simple loop, achieving the same result as the + operator.
def merge_lists(list_a, list_b):
merged = []
for item in list_a:
merged.append(item)
for item in list_b:
merged.append(item)
return merged
if __name__ == "__main__":
fruits = ["apple", "banana"]
vegetables = ["carrot", "spinach"]
result = merge_lists(fruits, vegetables)
…
How to Normalize a List of Numbers in Python
This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.
def normalize(data):
"""
Normalize a list of numeric values to the range [0, 1].
Returns a new list, leaving the original unchanged.
"""
if not data:
return []
min_val = min(data)
max_val = max(data)
# Handle the edge case where all values are identical
if min_val …
How to Parse Bullet Points in Python
Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.
def parse_bullet_points(text):
"""Extract bullet point items from raw text."""
lines = text.splitlines()
items = []
for line in lines:
stripped = line.strip()
if stripped.startswith("- ") or stripped.startswith("* "):
item = stripped[2:]
if item:
…
How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
def parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple…
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 into Words in Python
Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.
def convert_text_processor(text):
words = text.split()
processed = []
for word in words:
clean = word.strip('.,!?;:')
if len(clean) > 0:
processed.append(clean.upper())
return processed
if __name__ == "__main__":
sample_text = "Hello, world! This is a Python e…
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 Reverse a List in Place Without Using reverse() in Python
A two-pointer while loop swaps elements from both ends toward the center to reverse a list in place without creating a copy.
def reverse_list_in_place(lst):
left = 0
right = len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
print("Original:", my_list)
reverse_list_in_place(my_list)
prin…
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.