Cookbooks

Practical recipes for real-world Python programming tasks.

How to Convert a String to an Integer in Python

Convert strings to integers using int() with error handling for invalid input.

python conversion numbers strings

How to check if a key exists in a dictionary in Python

Check if a dictionary key exists using in, .get(), or catching KeyError. The in operator is the most Pythonic.

python dict dictionaries key

How to flatten a nested list in Python

Flatten a nested list using list comprehension, itertools, or recursion.

python lists nested

How to count occurrences of an item in a list in Python

Count how many times an element appears in a list using list.count(), Counter, or a manual loop.

python lists counting

How to get the current date and time in Python

Get the current date and time using datetime.now() or timezone-aware datetime with zoneinfo. Also covers date only and time only.

python datetime time dates

How to read a file line by line in Python

Read a file line by line using for loops, readlines(), or iter(). Compare memory efficiency and use cases.

python files io

How to find the maximum value in a list in Python

Find the maximum value in a list using max(), sorted(), or a loop. Includes handling empty lists and custom objects.

python lists beginner

How to Generate a Random Number in Python

Generate random numbers using the random module — integers, floats, and within ranges.

python random numbers

How to merge two dictionaries in Python

Merge dictionaries using the | operator, ** unpacking, or .update(). The | operator is the cleanest for Python 3.9+.

python dict dictionaries

How to Join a List into a String in Python

Learn how to convert a list to a string in Python using str.join, with examples for strings, numbers, custom separators, and edge cases.

python strings lists beginner

How to remove duplicates from a list in Python

Remove duplicates while preserving order using dict.fromkeys() or a loop. The simplest solution is list(dict.fromkeys(items)).

python lists deduplication

How to reverse a string in Python

Reverse a string using slicing or reversed(). The fastest method is slicing with [::-1].

python strings slicing

How to total a CSV column with csv.DictReader

Read a CSV file with csv.DictReader and total one column in Python with a simple loop.

python csv dictreader files

How to sort a list by a key in Python

Sort lists by custom criteria using the key parameter in sorted() and list.sort().

python lists sorting

How to Swap Two Variables in Python

Swap two variables in Python using tuple unpacking or a temporary variable. Tuple unpacking is the most Pythonic way.

python variables basics

How to write to a file in Python

Write text or binary data to files using Python built-in open function with different modes.

python files io