Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Find Local Minima (Valleys) in a Numeric List in Python
This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.
def find_local_minima(numbers):
"""Find indices of local minima (valleys) in a numeric list.
A value is a local minimum if it's less than or equal to its neighbors.
Edge elements are considered minima if they're less than or equal to their single neighbor.
"""
if not numbers:
return []…
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 Swap Two Indices in a Python List
Swap two elements at given indices in a Python list using simultaneous assignment, then return the modified list.
def swap_indices(lst, i, j):
lst[i], lst[j] = lst[j], lst[i]
return lst
if __name__ == "__main__":
my_list = [10, 20, 30, 40, 50]
print("Original list:", my_list)
swapped = swap_indices(my_list, 1, 3)
print("After swapping indices 1 and 3:", swapped)
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)
Reorder a List by Odd Even Indices in Python
Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.
def reorder_by_odd_even(items):
"""Reorders a list so that elements at odd indices come first,
followed by elements at even indices (1-based).
Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
"""
odds = [items[i] for i in range(1, len(items), 2)]
evens = [items[i] for i in range(0, len(items), …
Cosine Similarity to Retrieve Top K Chunks in Python
Compute cosine similarity between a query vector and a list of chunk vectors, then return the indices and scores of the top k most similar chunks.
import numpy as np
from numpy.linalg import norm
def cosine_similarity(vec1, vec2):
return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))
def retrieve_top_k(query_vec, chunk_vectors, k=3):
similarities = [cosine_similarity(query_vec, vec) for vec in chunk_vectors]
top_indices = sorted(range(len(similarit…
Z-Order Optimization in Python
A mock concept demonstrating z-order layout optimization by reassigning z-indices based on areas size.
class ZOrderLayout:
"""
Minimal mock for z-order layout optimization using a stacking score.
Elements overlap; higher z_index is drawn on top.
"""
def __init__(self):
self.elements = []
def add_element(self, name, area, z_index):
self.elements.append({"name": name, "area": area…
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.