32 Essential Python Tricks Every Developer Should Know
This article presents 32 practical Python tips ranging from one‑line variable swapping and chained comparisons to debugging with pdb, memory optimization with __slots__, and implementing switch‑case logic, providing concise code examples that boost productivity and code readability.
1. Swap two numbers in place
Python allows swapping variables in a single line using tuple unpacking.
x, y = 10, 20
print(x, y) # 10 20
x, y = y, x
print(x, y) # 20 102. Chained comparison operators
Multiple comparisons can be combined in a single expression.
n = 10
result = 1 < n < 20 # True
result = 1 > n <= 9 # False3. Conditional assignment with ternary operator
The ternary operator provides a compact form of an if‑else statement.
x = 10 if (y == 9) else 20
x = (classA if y == 1 else classB)(param1, param2)4. Multi‑line strings
Use a backslash or triple quotes to create strings that span several lines.
multistr = "select * from multi_row \" \
"where row_id < 5"
# or
multistr = """select * from multi_row
where row_id < 5"""
# or using parentheses for clean concatenation
multistr = ("select * from multi_row "
"where row_id < 5"
" orderby age")5. Store list elements into separate variables
Unpack a list directly into multiple variables.
testlist = [1, 2, 3]
x, y, z = testlist
print(x, y, z) # 1 2 36. Print the file path of an imported module
Display the absolute path of a module by printing the module object.
import threading, socket
print(threading) # <module 'threading' from '/usr/local/lib/python3.5/threading.py'>
print(socket) # <module 'socket' from '/usr/local/lib/python3.5/socket.py'>7. The "_" placeholder in interactive sessions
"_" holds the result of the last expression in the REPL.
2 + 3 # => 5
_ # => 5
print(_) # prints 58. Dictionary and set comprehensions
Similar to list comprehensions, they create dictionaries or sets in a single line.
testDict = {i: i*i for i in range(5)}
testSet = {i*2 for i in range(5)}9. Debugging with pdb
Insert pdb.set_trace() to set a breakpoint; common commands include break (b), continue (c), list (l), step (s), return (r), quit (q), next (n), clear, and print (p).
break or b – set a breakpoint
continue or c – resume execution until next breakpoint
list or l – show surrounding source code
step or s – step into a function
return or r – run until the current function returns
quit or q – exit the debugger
next or n – execute the next line
clear – remove a breakpoint
p or pp – print the value of an expression
import pdb
pdb.set_trace()10. Start a simple HTTP file server
Run a one‑liner to serve files from the current directory (default port 8000).
python3 -m http.server
# or specify a custom port: python3 -m http.server 808011. Inspect an object with dir()
List all attributes and methods of an object.
test = [1, 3, 5, 7]
print(dir(test))12. Simplify if statements with in
Check membership instead of chaining equality tests.
if m in [1, 3, 5, 7]:
...
# equivalent to
if m == 1 or m == 3 or m == 5 or m == 7:
...13. Detect the running Python version
Exit gracefully if the interpreter is older than the required version.
import sys
if not hasattr(sys, "hexversion") or sys.hexversion != 0x03050080:
print("Sorry, you aren't running on Python 3.5")
sys.exit(1)
print("Current Python version:", sys.version)14. Concatenate all strings in a list
Use ''.join() for fast concatenation.
test = ['I', 'Like', 'Python', 'automation']
result = ''.join(test) # 'ILikePythonautomation'15. Four ways to reverse a sequence
Reverse a list in place, iterate with reversed(), slice syntax for strings, and slice syntax for lists.
# in‑place
lst = [1, 3, 5]
lst.reverse() # [5, 3, 1]
# iterator
for e in reversed([1, 3, 5]):
print(e) # 5 3 1
# string slice
"Test Python"[::-1] # 'nohtyP tseT'
# list slice
[1, 3, 5][::-1] # [5, 3, 1]16. Build a dictionary from two related sequences
t1 = (1, 2, 3)
t2 = (10, 20, 30)
result = dict(zip(t1, t2)) # {1: 10, 2: 20, 3: 30}17. Split a dictionary into separate key and value lists
c = {'Bob': 'male', 'Jack': 'male', 'Mary': 'female', 'Tom': 'male'}
keys = list(c.keys())
values = list(c.values())18. Compute a factorial in one line
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3) # 619. Find the most frequent element in a list
test = [1,2,3,4,2,2,3,1,4,4,4]
most_common = max(set(test), key=test.count) # 420. Reset the recursion limit
import sys
print(sys.getrecursionlimit()) # 1000
sys.setrecursionlimit(1500)
print(sys.getrecursionlimit()) # 150021. Check an object's memory usage
import sys
x = 1
print(sys.getsizeof(x)) # 28 bytes on Python 3.522. Reduce memory consumption with __slots__
Define __slots__ to avoid per‑instance __dict__ overhead.
class FileSystem:
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices
class FileSystemSlots:
__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices23. Mimic a switch‑case with a dictionary
def xswitch(key):
return xswitch._map.get(key)
xswitch._map = {'files': 10, 'folders': 5, 'devices': 2}
print(xswitch('devices')) # 2
print(xswitch('unknown')) # None24. Count items with collections.Counter
from collections import Counter
c = Counter('hello world')
print(c.most_common(2)) # [('l', 3), ('o', 2)]25. Pretty‑print JSON
import json
data = {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz"}, {"age": 29, "name": "Joe"}]}
print(json.dumps(data, indent=2))26. Use enumerate for indexed loops (implicit in many snippets)
Enumerate provides both index and value in a single construct.
for i, val in enumerate(['a', 'b', 'c']):
print(i, val)27. Store multiple return values
def foo():
return 1, 2, 3, 4
a, b, c, d = foo()
print(a, b, c, d) # 1 2 3 428. Search for multiple prefixes or suffixes
url = "http://www.google.com"
print(url.startswith(("http://", "https://"))) # True
print(url.endswith((".com", ".co.uk"))) # True29. Flatten a list without an explicit loop
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
flat = list(itertools.chain.from_iterable(test))
# [-1, -2, 30, 40, 25, 35]30. Implement a true switch‑case using a dictionary
def xswitch(key):
return xswitch._cases.get(key)
xswitch._cases = {'files': 10, 'folders': 5, 'devices': 2}
print(xswitch('devices')) # 231. Use lambda to create a lightweight print function
import sys
lprint = lambda *args: sys.stdout.write(''.join(map(str, args)))
lprint('python', 'tips', 1000, 1001)
# outputs: pythontips100010011832. Store operations in a dictionary for quick lookup
stdacl = {'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y}
print(stdacl['sum'](9, 3)) # 12
print(stdacl['subtract'](9, 3)) # 6Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
