pyguides

Cookbooks

Cookbooks

Practical recipes for real-world Python programming tasks.

  1. 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.

  2. How to Convert a String to an Integer in Python

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

  3. How to flatten a nested list in Python

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

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. How to merge two dictionaries in Python

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

  9. How to Generate a Random Number in Python

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

  10. 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.

  11. 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)).

  12. How to sort a list by a key in Python

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

  13. How to reverse a string in Python

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

  14. 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.

  15. 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.

  16. How to write to a file in Python

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