Python Tips and Tricks: Variable Swapping, Chain Comparisons, Ternary Operators, and More
This article presents a collection of practical Python techniques—including one‑line variable swapping, chained comparisons, ternary conditional assignments, multi‑line strings, list unpacking, module path printing, interactive underscore usage, comprehensions, debugging, simple HTTP serving, memory inspection, and simulated switch‑case—each illustrated with concise code examples.
Python provides a concise one‑line syntax for simultaneous assignment and swapping of variables; the right‑hand side creates a temporary tuple that is immediately unpacked into the left‑hand side.
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y) # (10, 20) then (20, 10)Chained comparison operators allow expressions like 1 < n < 20 to be written compactly, returning a Boolean result.
n = 10
result = 1 < n < 20
print(result) # True
result = 1 > n <= 9
print(result) # FalseThe ternary (conditional) operator offers a short form of if‑else statements: [true‑value] if [condition] else [false‑value]. x = 10 if (y == 9) else 20 Similar conditional expressions can be used when constructing objects, e.g., selecting a class based on a condition.
x = (classA if y == 1 else classB)(param1, param2)Multi‑line strings can be created using backslashes, triple quotes, or by concatenating strings inside parentheses to avoid unwanted indentation.
multiStr = "select * from multi_row where row_id < 5"
print(multiStr)
multiStr = """select * from multi_row where row_id < 5"""
print(multiStr)
multiStr = ("select * from multi_row "
"where row_id < 5 "
"order by age")
print(multiStr)Lists can be unpacked directly into variables, provided the number of variables matches the list length.
testList = [1, 2, 3]
x, y, z = testList
print(x, y, z) # -> 1 2 3To display the absolute file path of an imported module, simply print the module object.
import threading, socket
print(threading)
print(socket)In the interactive Python shell, the underscore variable _ holds the result of the last evaluated expression.
>> 2 + 13
>>> _
15
>>> print(_)
15Dictionary and set comprehensions provide a compact way to generate mappings and collections.
testDict = {i: i*i for i in range(10)}
testSet = {i*2 for i in range(10)}
print(testSet)
print(testDict)Debugging can be performed by inserting a breakpoint with the pdb module.
import pdb
pdb.set_trace()A quick HTTP file server can be started from the command line using the built‑in modules.
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.serverThe dir() function lists the attributes and methods of an object.
test = [1, 3, 5, 7]
print(dir(test))Multiple value checks can be simplified with the in operator, and using a set instead of a list gives O(1) lookup.
if m in {1, 3, 5, 7}:
...A one‑liner factorial can be written using functools.reduce and a lambda.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result) # -> 6Finding the most frequent element in a list can be done with max(set(...), key=list.count).
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count)) # -> 4The recursion limit can be queried and increased with sys.getrecursionlimit() and sys.setrecursionlimit().
import sys
print(sys.getrecursionlimit()) # 1000
sys.setrecursionlimit(1001)
print(sys.getrecursionlimit()) # 1001Memory usage of objects can be measured with sys.getsizeof(), showing differences between Python 2 and 3.
import sys
x = 1
print(sys.getsizeof(x)) # 24 (Py2) or 28 (Py3)Defining __slots__ in a class can reduce per‑instance memory overhead by preventing the creation of a __dict__ for each object.
class FileSystem(object):
__slots__ = ['files', 'folders', 'devices']
def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devicesA lambda can be used to create a lightweight print‑like function.
import sys
lprint = lambda *args: sys.stdout.write(' '.join(map(str, args)))
lprint('python', 'tips', 1000, 1001)
# -> python tips 1000 1001Two related sequences can be combined into a dictionary using zip() and dict().
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict(zip(t1, t2))) # {1: 10, 2: 20, 3: 30}String prefix and suffix checks can be performed with startswith() and endswith() using tuples.
print('http://www.google.com'.startswith(('http://', 'https://')))
print('http://www.google.co.uk'.endswith(('.com', '.co.uk')))
# True TrueA list can be flattened without an explicit loop using itertools.chain.from_iterable().
import itertools
test = [[-1,-2],[30,40],[25,35]]
print(list(itertools.chain.from_iterable(test)))
# -> [-1, -2, 30, 40, 25, 35]A switch‑case style construct can be simulated with a dictionary and a helper function.
def xswitch(x):
return xswitch._system_dict.get(x, None)
xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}
print(xswitch('default')) # None
print(xswitch('devices')) # 2Signed-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.
