Examples

Python examples

20 runnable Python examples — every snippet executes on the real CompileBytes engine, right on the page. Copy it, edit it, and run it again. No setup or signup.

20 of 20
How to reverse a string in Python
Three ways to reverse a string — slicing, reversed() + join(), and a loop — plus how to reverse the words in a sentence.
View →
How to remove duplicates from a list in Python
Remove duplicate items from a list — dict.fromkeys() (keeps order), set() (fastest), and a loop — plus how to dedupe unhashable items like dicts.
View →
How to merge two dictionaries in Python
Merge two dictionaries — the | operator (3.9+), {**a, **b} unpacking, and .update() — plus how to deep-merge nested dicts. See which mutates and which builds a new dict.
View →
How to flatten a list of lists in Python
Make a flat list out of a list of lists — a nested comprehension, itertools.chain.from_iterable(), and sum(nested, []) — plus how to flatten arbitrarily nested lists.
View →
How to find the index of a list item in Python
Find the index of an item in a list — list.index() for the first match, an in-guard or try/except for missing items, and an enumerate() comprehension for every index — plus finding the first item that matches a condition.
View →
How to get the current date and time in Python
Get the current date and time with datetime.now(), format it with strftime(), make it timezone-aware with timezone.utc or ZoneInfo, and read the clock as a Unix timestamp.
View →
How to convert bytes to a string in Python
Decode bytes to str with .decode(), why str(b) gives you b'...' instead, how to survive a UnicodeDecodeError, and where bytes come from in the first place.
View →
How to list all files in a directory in Python
List a folder with os.listdir() and Path.iterdir(), keep only the files, match patterns with glob, walk subfolders recursively, and read sizes with os.scandir().
View →
How to concatenate two lists in Python
Four ways to concatenate lists — the + operator, extend() / += in place, unpacking with [*a, *b], and itertools.chain — plus the aliasing gotcha += hides.
View →
How to check if a list is empty in Python
Check whether a list is empty — the truthiness test if not items:, len(items) == 0, and why items == [] is discouraged — plus how to tell an empty list from None.
View →
How to slice a list in Python
Slice a list with items[start:stop] — the half-open rule, omitted ends, negative indices, the step argument, and slice assignment to edit a list in place.
View →
How to count occurrences in a list in Python
Count how often items appear in a list — list.count() for a single value, collections.Counter for all of them in one pass, sum() with a condition, and a plain dict tally.
View →
How to remove a key from a dictionary in Python
Remove a key from a dict — del for keys that must exist, pop() when you want the removed value, pop(key, None) to never raise — plus a comprehension that drops several keys at once.
View →
How to check if a key exists in a dictionary in Python
Four ways to check for a dictionary key — the in operator, dict.get() with a default, try/except KeyError, and setdefault() — plus the falsy-value trap that breaks if d.get(key).
View →
How to sort a dictionary by value in Python
Sort a dictionary by value — sorted() on .items() with a lambda, operator.itemgetter(1), reverse=True for descending, a tuple key for ties, and Counter.most_common() for counts.
View →
How to convert two lists into a dictionary in Python
Turn a list of keys and a list of values into a dict — dict(zip(...)), zip(strict=True), a dict comprehension, and itertools.zip_longest — plus what happens on uneven lengths and duplicate keys.
View →
How to check if a string contains a substring in Python
Check whether a string contains a substring with the in operator, find() and index() when you need the position, casefold() for case-insensitive matching, and re.search() for patterns.
View →
How to join a list into a string in Python
Join a list into a string with ", ".join(items) — plus map(str, ...) for lists of numbers, "\n".join() for line-by-line output, and why += in a loop is the wrong tool.
View →
How to convert a string to an int in Python
Turn a string into an int with int() — plus try/except ValueError for untrusted input, int(float()) for decimal strings, int(s, base) for binary and hex, and how to convert a whole list.
View →
How to loop with an index in Python
Loop with an index in Python — enumerate(), enumerate(items, start=1) for human-facing numbering, the range(len()) habit to avoid, and zip() for walking two lists together.
View →
Same task, different syntax

Examples in other languages

Compare how familiar programming tasks look across the catalog.

FAQ

Python examples, explained

Can I run the code on this page?+
Yes. Every Python example is a live snippet that runs on the CompileBytes engine. You can edit and rerun it without installing anything.
Is this free? Do I need an account?+
Every example is free to read, run, edit, and copy. No account is required.
Can I copy these into my own projects?+
Yes. These examples are designed to be copied and adapted to your own code.
Where can I run my own code?+
Open the Python compiler from the main playground catalog, then paste or write any code you want to run.