Top 30 Trending Python Coding Examples

To understand these Python examples, you should know the following:

1. Write a Python function to reverse a string using slicing

Code:

def reverse_string(s):
    return s[::-1]

print(reverse_string("Python"))

Output:

nohtyP

Explanation:

s[::-1] uses extended slice syntax [start:stop:step]. Setting step to -1 traverses the string backward.

2. Write a Python function to check if a string reads the same backward as forward

Code:

def is_palindrome(s):
    clean_s = s.lower().replace(" ", "")
    return clean_s == clean_s[::-1]

print(is_palindrome("Race car"))

Output:

True

Explanation:

Converts the string to lowercase and removes spaces before checking if it matches its reverse.

3. Flatten a multi-level nested Python list into a single flat list using list comprehension

Code:

nested = [[1, 2], [3, 4, 5], [6]]
flattened = [item for sublist in nested for item in sublist]
print(flattened)

Output:

[1, 2, 3, 4, 5, 6]

Explanation:

The double for loop inside the list comprehension iterates through each sublist and extracts individual elements.

4. Find two indices in an array whose values sum up to a target number in Python

Code:

def two_sum(nums, target):
    seen = {}
    for idx, num in enumerate(nums):
        diff = target - num
        if diff in seen:
            return [seen, idx]
        seen[num] = idx

print(two_sum([2, 7, 11, 15], 9))

Output:

[0, 1]

Explanation:

Uses a dictionary to store seen numbers and their indices for an efficient O(n) time complexity lookup.

5. Count the frequency of characters in a string using Python collections.Counter

Code:

from collections import Counter

counts = Counter("banana")
print(dict(counts))

Output:

{'b': 1, 'a': 3, 'n': 2}

Explanation:

Counter is a dictionary subclass designed to automatically tally hashable objects.

6. Merge two dictionaries using Python’s dictionary union operator |

Code:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 99, "c": 3}
merged = dict1 | dict2
print(merged)

Output:

{'a': 1, 'b': 99, 'c': 3}

Explanation:

The | operator merges two dictionaries, letting keys from the right operand overwrite matching keys from the left.

7. Create a Python generator function that yields Fibonacci numbers up to n terms

Code:

def fibonacci_gen(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fibonacci_gen(6)))

Output:

[0, 1, 1, 2, 3, 5]

Explanation:

The yield keyword pauses state execution, generating values one at a time with minimal memory overhead.

8. Determine if two strings are anagrams of each other in Python

Code:

from collections import Counter

def is_anagram(s1, s2):
    return Counter(s1) == Counter(s2)

print(is_anagram("listen", "silent"))

Output:

True

Explanation:

Compares character frequencies using Counter. If frequency counts match, the words are anagrams.

9. Identify duplicate elements in a list while preserving order in Python

Code:

items = [1, 2, 3, 2, 4, 5, 1, 6]
seen = set()
duplicates = set(x for x in items if x in seen or seen.add(x))
print(list(duplicates))

Output:

[1, 2]

Explanation:

seen.add(x) returns None (falsy), so x in seen triggers first, allowing single-pass duplicate extraction.

10. Search for a target value in a sorted array using binary search in Python

Code:

def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([10, 20, 30, 40, 50], 40))

Output:

3

Explanation:

Halves the search space at each iteration, operating in O(log n) logarithmic time complexity.

11. Write a custom Python decorator to measure the execution time of a function

Code:

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"Executed in {end - start:.4f}s")
        return result
    return wrapper

@timer
def compute():
    return sum(i * i for i in range(1000000))

compute()

Output:

Executed in 0.0521s

Explanation:

Wraps the target function to record high-resolution timestamps immediately before and after execution.

12. Split a list into sublists of size n in Python

Code:

def chunk_list(lst, n):
    return [lst[i:i + n] for i in range(0, len(lst), n)]

print(chunk_list([1, 2, 3, 4, 5, 6, 7], 3))

Output:

[[1, 2, 3], [4, 5, 6], [7]]

Explanation:

Uses list comprehension over step indices (range(0, len(lst), n)) to yield slices of length n.

13. Implement a custom context manager using @contextmanager in Python

Code:

from contextlib import contextmanager

@contextmanager
def managed_message():
    print("Starting task...")
    yield
    print("Task completed safely.")

with managed_message():
    print("Processing data...")

Output:

Starting task...
Processing data...
Task completed safely.

Explanation:

@contextmanager allows generator functions to handle setup before yield and cleanup operations after yield.

14. Create a structured data container using Python dataclasses and type annotations

Code:

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float
    in_stock: bool = True

p = Product(name="Keyboard", price=49.99)
print(p)

Output:

Product(name='Keyboard', price=49.99, in_stock=True)

Explanation:

@dataclass automatically generates __init__, __repr__, and __eq__ methods based on type annotations.

15. Optimize a recursive function using built-in @lru_cache in Python

Code:

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(50))

Output:

12586269025

Explanation:

@lru_cache memoizes function call outputs, turning exponential recursion into linear O(n) time.

16. Write a classic Merge Sort algorithm in Python

Code:

def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    
    merged = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            merged.append(left[i]); i += 1
        else:
            merged.append(right[j]); j += 1
    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))

Output:

[3, 9, 10, 27, 38, 43, 82]

Explanation:

Divide-and-conquer strategy recursively splits the array in half and merges sorted halves back together in O(n log n) time.

17. Parse a JSON string into a Python object safely

Code:

import json

raw_json = '{"user": "Alex", "active": true, "roles": ["Admin", "Dev"]}'
data = json.loads(raw_json)
print(data["roles"][0])

Output:

Admin

Explanation:

json.loads() parses JSON-formatted strings into native Python dictionaries and lists.

18. Iterate over a Python list with both element index and custom starting position

Code:

tasks = ["Design", "Develop", "Test"]
for idx, task in enumerate(tasks, start=1):
    print(f"{idx}: {task}")

Output:

1: Design
2: Develop
3: Test

Explanation:

enumerate(iterable, start) yields tuples containing a counter starting at start along with corresponding list values.

19. Combine two Python lists into pairs, then transpose (unzip) them back into original lists

Code:

names = ["Alice", "Bob"]
scores = [85, 92]

zipped = list(zip(names, scores))
unzipped_names, unzipped_scores = zip(*zipped)

print("Zipped:", zipped)
print("Unzipped Names:", unzipped_names)

Output:

Zipped: [('Alice', 85), ('Bob', 92)]
Unzipped Names: ('Alice', 'Bob')

Explanation:

zip() pairs elements positional-wise. Passing *zipped back into zip() reverses the pairing operation.

20. Execute concurrent asynchronous tasks using asyncio.gather in Python

Code:

import asyncio

async def fetch_data(id, delay):
    await asyncio.sleep(delay)
    return f"Response {id}"

async def main():
    results = await asyncio.gather(
        fetch_data(1, 0.2),
        fetch_data(2, 0.1)
    )
    print(results)

asyncio.run(main())

Output:

['Response 1', 'Response 2']

Explanation:

asyncio.gather() runs multiple asynchronous coroutines concurrently without blocking execution.

21. Extract domain names from email addresses using Regular Expressions in Python

Code:

import re

email = "user.name@company.org"
match = re.search(r'@([\w.-]+)', email)
if match:
    print(match.group(1))

Output:

company.org

Explanation:

re.search scans for matches. Pattern @([\w.-]+) captures all letters, digits, dots, or hyphens following @.

22. Group consecutive elements in a sequence by key attributes in Python

Code:

from itertools import groupby

words = ["apple", "apricot", "banana", "berry", "cherry"]
for key, group in groupby(words, key=lambda x: x[0]):
    print(key, list(group))

Output:

a ['apple', 'apricot']
b ['banana', 'berry']
c ['cherry']

Explanation:

groupby() collects consecutive identical key outputs produced by the key callback function. Input must be sorted by key first.

23. Validate if a string represents a valid 24-hour military time string (HH:MM) in Python

Code:

import re

def is_valid_time(t):
    pattern = r'^(?:[01]\d|2[0-3]):[0-5]\d$'
    return bool(re.match(pattern, t))

print(is_valid_time("23:59"))
print(is_valid_time("24:00"))

Output:

True
False

Explanation:

Ensures hours range from 00-23 and minutes range from 00-59 using regex boundaries.

24. Sort a list of dictionaries by a specific dictionary key value in Python

Code:

users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 25}
]
sorted_users = sorted(users, key=lambda x: x["age"])
print(sorted_users)

Output:

[{'name': 'Bob', 'age': 22}, {'name': 'Charlie', 'age': 25}, {'name': 'Alice', 'age': 30}]

Explanation:

Passes a lambda callback function to sorted() as the extraction key during sort comparisons.

25. Transpose a 2D matrix (rows become columns) in Python

Code:

matrix = [
    [1, 2, 3],
    [4, 5, 6]
]
transposed = [list(col) for col in zip(*matrix)]
print(transposed)

Output:

[[1, 4], [2, 5], [3, 6]]

Explanation:

Unpacks rows via *matrix into zip(), grouping column positions into transposed rows.

26. Write a recursive function in Python to flatten key paths in nested dictionaries

Code:

def flatten_dict(d, parent_key='', sep='.'):
    items = []
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

nested = {"a": 1, "b": {"c": 2, "d": {"e": 3}}}
print(flatten_dict(nested))

Output:

{'a': 1, 'b.c': 2, 'b.d.e': 3}

Explanation:

Recursively concatenates key paths separated by . whenever the value encountered is an inner dictionary.

27. Retrieve a key value from a Python dictionary safely without raising KeyError

Code:

config = {"theme": "dark"}
font = config.get("font", "Arial")
print("Font:", font)

Output:

Font: Arial

Explanation:

dict.get(key, default) returns the default parameter value (Arial) if the targeted key is missing.

28. Find common elements present across multiple list sequences in Python

Code:

l1 = [1, 2, 3, 4, 5]
l2 = [3, 4, 5, 6]
l3 = [5, 6, 7, 3]

common = set(l1).intersection(l2, l3)
print(sorted(list(common)))

Output:

[3, 5]

Explanation:

set.intersection() computes set-theoretic overlap across multiple input collections simultaneously.

29. Write a resilient retry mechanism with exponential backoff strategy for failing operations in Python

Code:

import time

def retry(max_retries=3):
    for attempt in range(max_retries):
        try:
            if attempt < 1:
                raise ValueError("Network timeout")
            return "Success!"
        except Exception as e:
            wait = 2 ** attempt
            print(f"Attempt {attempt+1} failed ({e}). Retrying in {wait}s...")
            time.sleep(wait)

print(retry())

Output:

Attempt 1 failed (Network timeout). Retrying in 1s...
Success!

Explanation:

Calculates delay via exponentiation (2 ** attempt) to prevent pounding unstable services with rapid retry requests.

30. Use Python pattern matching (match-case) to handle API status responses

Code:

def handle_status(status_code):
    match status_code:
        case 200 | 201:
            return "Request Succeeded"
        case 404:
            return "Resource Not Found"
        case 500 | 502 | 503:
            return "Server Error"
        case _:
            return "Unknown Status"

print(handle_status(404))
print(handle_status(200))

Output:

Resource Not Found
Request Succeeded

Explanation:

Uses structural pattern matching (match-case). The | acts as an OR condition, and _ serves as the wildcard catch-all case.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

Python Exception Handling
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment