Python Snippets & Tutorials

Python snippets and short guides for common tasks: string handling, file I/O, lists, dicts, and basic logic.

Whether you’re writing a quick script or building something larger, the examples here are self-contained: run them in the REPL or drop them into your file. We assume you have Python 3 installed; where a snippet needs PHP 8+ or a specific library, we say so.

Reverse a string in Python

s = "Hello"
reversed_s = s[::-1]
print(reversed_s)  # olleH

Slice [::-1] steps backward through the string. For a recursive version or loop-based approach, the idea is the same: build the new string from the end. This works on any sequence (lists, tuples) as well.

Check if a dictionary is empty

data = {}
if not data:
    print("Dictionary is empty")

# Or explicitly:
if len(data) == 0:
    print("Dictionary is empty")

In Python, an empty dict is falsy, so if not data is the usual idiom. Use len(data) == 0 if you want to be explicit. Both are constant time.

Get the length of a file (line count)

with open("myfile.txt", "r") as f:
    line_count = sum(1 for _ in f)
print(line_count)

This reads the file once and counts lines without loading everything into memory. For a rough byte size you can use os.path.getsize("myfile.txt") or Path("myfile.txt").stat().st_size.

Nth root using math

import math
x = 27
n = 3
root = math.pow(x, 1 / n)  # 3.0 (cube root of 27)

math.pow(x, 1/n) gives the n-th root of x. For square root, use math.sqrt(x) or x ** 0.5.

More Python topics

See also: Learn to Code and Code Snippets.