Python How-To Guides

Quick answers to the questions people actually search for. Each guide starts with the shortest working answer, then shows alternatives, pitfalls and when to use which.

Converting data

How to Convert a String to an Int in Python
Use `int(text)`, for example `int("42")` returns `42`. If the string is not a whole number, such as `"3.7"` or `"abc"`, `int()` r…
How to Convert an Int to a String in Python
Use `str(number)`, for example `str(42)` returns `"42"`. For formatting such as padding or commas, use an [f-string](/python-f-st…
How to Convert a List to a String in Python
Use `", ".join(items)` to glue a list of strings into one string. If the list holds numbers, convert them first: `", ".join(map(s…
How to Convert a String to a List in Python
Use `text.split()` to get a list of words, `text.split(",")` to split on a separator, or `list(text)` to get a list of single cha…
How to Convert a String to a Float in Python
Use `float(text)`, for example `float("3.14")` returns `3.14`. Text that is not a number, such as `"abc"` or `"1,234.5"`, raises …
How to Convert a Float to an Int in Python
`int(3.9)` returns `3` because it cuts off the decimal part. Use `round(3.9)` to get `4`, or `math.floor()` and `math.ceil()` to …
How to Convert a List to a Dictionary in Python
Use `dict(zip(keys, values))` to build a dictionary from two lists, or `dict(list_of_pairs)` when each item is already a `(key, v…
How to Convert a Tuple to a List in Python
Use `list(my_tuple)`, for example `list((1, 2, 3))` returns `[1, 2, 3]`. The unpacking form `[*my_tuple]` does the same.
How to Convert a String to a Datetime in Python
Use `datetime.strptime(text, format)`, for example `datetime.strptime("2026-03-15", "%Y-%m-%d")`. For ISO 8601 text, `datetime.fr…
How to Convert JSON to a Dictionary in Python
Use `json.loads(text)` to turn a JSON string into a dictionary, or `json.load(file)` to read it from an open file.

Working with text

How to Reverse a String in Python
Use slicing: `text[::-1]` returns a new string with the characters in reverse order. `"".join(reversed(text))` does the same thin…
How to Check if a String Contains a Substring in Python
Use the `in` operator: `"cat" in "concatenate"` returns `True` if the substring appears anywhere in the string and `False` otherw…
How to Remove Whitespace from a String in Python
Use `text.strip()` to remove whitespace from both ends, or `"".join(text.split())` to remove it everywhere, including spaces, tab…
How to Split a String into Words in Python
Call `text.split()` with no arguments: it splits on any whitespace and returns a list of words, such as `"to be or not".split()` …
How to Compare Strings Ignoring Case in Python
Convert both strings to the same case before comparing: `a.casefold() == b.casefold()` (or `a.lower() == b.lower()`) is `True` wh…
How to Pad a Number with Leading Zeros in Python
Use an f-string: `f"{7:03d}"` gives `'007'`. For text that is already a string, `"7".zfill(3)` gives the same `'007'`.
How to Capitalize the First Letter of a String in Python
`text.capitalize()` uppercases the first character and lowercases the rest; use `text[0].upper() + text[1:]` to change only the f…

Lists, dicts and sets

How to Remove Duplicates from a List in Python
Use `list(dict.fromkeys(items))` to remove duplicates **and keep the original order**. Use `list(set(items))` when order does not…
How to Sort a Dictionary by Value in Python
Use `dict(sorted(d.items(), key=lambda item: item[1]))` to sort a dictionary by value, and add `reverse=True` for descending orde…
How to Merge Two Dictionaries in Python
Use `merged = a | b` (Python 3.9+) or `merged = {**a, **b}` to merge two dictionaries into a new one. If both have the same key, …
How to Reverse a List in Python
Use `my_list.reverse()` to reverse a list **in place**, or `my_list[::-1]` to get a **new** reversed list. `reversed(my_list)` gi…
How to Flatten a List of Lists in Python
To flatten a list of lists one level, use `[x for row in nested for x in row]` or `list(itertools.chain.from_iterable(nested))`. …
How to Check if a List Is Empty in Python
Write `if not my_list:` to check whether a list is empty. An empty list is falsy, so `not my_list` is `True` only when the list h…
How to Get the Last Element of a List in Python
Use `my_list[-1]` to get the last element of a list. A negative index counts from the end, so `-1` is the last item and `-2` the …
How to Loop Through a Dictionary in Python
Use `for key, value in my_dict.items():` to loop over keys and values together. Loop over `my_dict` (or `.keys()`) for keys only …
How to Count Occurrences in a List in Python
Use `my_list.count(item)` to count one item, or `collections.Counter(my_list)` to count every item in a single pass. `Counter(my_…

Files and data

How to Read a File Line by Line in Python
Open the file with `with open("file.txt") as f:` and loop over it: `for line in f:`. Each `line` is one line of text, including i…
How to Write to a File in Python
Use `with open("notes.txt", "w", encoding="utf-8") as f:` then `f.write("text\n")`. Mode `"w"` replaces the file; mode `"a"` adds…
How to Read a CSV File in Python
Use the `csv` module: `with open("data.csv", newline="", encoding="utf-8") as f:` then `csv.DictReader(f)` gives each row as a di…
How to Read a JSON File in Python
Open the file and call `json.load()`: `with open("data.json", encoding="utf-8") as f: data = json.load(f)`. You get ordinary dict…
How to Check if a File Exists in Python
Use `pathlib`: `Path("data.txt").is_file()` is `True` only if the path exists and is a regular file. `Path(...).exists()` is `Tru…

Setup and tooling

How to Install a Package with pip in Python
Run `python -m pip install package_name` in your terminal (not inside the Python prompt). Using `python -m pip` guarantees the pa…
How to Create a Virtual Environment in Python
Run `python -m venv .venv` in your project folder, then activate it with `source .venv/bin/activate` (macOS and Linux) or `.venv\…
How to Run a Python Script from the Command Line
Save your code in a file such as `hello.py`, open a terminal in that folder and run `python hello.py` (or `python3 hello.py` on m…

Explore more

Python ReferencePython ProgramsPython ComparisonsPython Cheat SheetsPython glossaryPython tutorial