Back to Cheat Sheets

Python One-Liners & Tips

Common Python one-liners, tricks, and utilities for quick development tasks.

Action Command Details
List comprehension [x**2 for x in range(10)] Generate a list of squares from 0 to 9.
Reverse string 'hello'[::-1] Reverse the string 'hello' to 'olleh'.
Sort list sorted([3,1,2]) Return a sorted copy of the list.
Count items collections.Counter(list) Count frequency of items in a list. Requires 'import collections'.
Merge dicts {**dict1, **dict2} Merge two dictionaries (Python 3.5+).
Swap values a, b = b, a Swap the values of variables a and b.
Check even lambda x: x % 2 == 0 Anonymous function to check if a number is even.
Read file open('file.txt').read() Read entire file content as a string.
Write file open('file.txt', 'w').write('Hello') Write 'Hello' to a file, overwriting it.
HTTP request import requests; requests.get(url).text Perform a GET request using the requests library.
JSON handling import json; json.loads(data) Parse JSON string into Python objects.
Timing import time; start=time.time() Record start time for execution timing.
Filter list list(filter(lambda x: x > 5, items)) Filter items greater than 5.
Lambda map list(map(lambda x: x*2, items)) Double each item in a list.
Set comprehension {x for x in items if x > 0} Create a set of positive items.
Dictionary comprehension {k:v for k,v in iterable} Construct a dictionary using comprehension.
Flatten list [y for x in list_of_lists for y in x] Flatten a list of lists into a single list.
Check if file exists import os; os.path.exists('file.txt') Check presence of a file.
Print formatted string f'Name: {name}, Age: {age}' Use f-strings for inline variable substitution.
LoopPlunk
Support Us