Fundamentals 15 min read

30 Useful Python Programming Tips and Tricks

This article compiles thirty concise Python programming tricks—including variable swapping, chained comparisons, ternary operators, multi‑line strings, list unpacking, module path inspection, debugging, HTTP serving, memory checks, and custom switch‑case emulation—to help developers write cleaner, more efficient code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
30 Useful Python Programming Tips and Tricks

This article compiles thirty concise Python programming tricks—including variable swapping, chained comparisons, ternary operators, multi‑line strings, list unpacking, module path inspection, debugging, HTTP serving, memory checks, and custom switch‑case emulation—to help developers write cleaner, more efficient code.

1. Directly swap two numbers

Python allows simultaneous assignment to exchange values in one line.

x, y = 10, 20
print(x, y)

x, y = y, x
print(x, y)

2. Chained comparison operators

Multiple comparisons can be combined in a single expression.

n = 10
result = 1 < n < 20
print(result)  # True

result = 1 > n <= 9
print(result)  # False

3. Ternary conditional operator

Use the inline [on_true] if [condition] else [on_false] syntax for compact assignments.

x = 10 if (y == 9) else 20

4. Multi‑line strings

Combine lines with backslashes or triple quotes, or concatenate strings inside parentheses.

multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)

multiStr = """select * from multi_row 
where row_id < 5"""
print(multiStr)

5. Unpack list elements into variables

testList = [1,2,3]
x, y, z = testList
print(x, y, z)

6. Print imported module file paths

import threading, socket
print(threading)
print(socket)

7. Interactive "_" placeholder

In the REPL, _ holds the result of the last expression.

>> 2 + 1
3
>>> _
3
>>> print(_)
3

8. Dictionary and set comprehensions

testDict = {i: i*i for i in range(10)}
testSet = {i*2 for i in range(10)}
print(testSet)
print(testDict)

9. Debugging with pdb

import pdb
pdb.set_trace()

10. Quick file sharing via HTTP server

# Python 2:
python -m SimpleHTTPServer
# Python 3:
python3 -m http.server

11. Inspect object attributes

test = [1,3,5,7]
print(dir(test))

12. Simplify if with in

if m in [1,3,5,7]:
    ...
# equivalent to
if m == 1 or m == 3 or m == 5 or m == 7:
    ...

13. Detect Python version at runtime

import sys
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
    print("Sorry, you aren't running on Python 3.5")
    sys.exit(1)
print("Current Python version:", sys.version)

14. Concatenate strings from a list

test = ['I', 'Like', 'Python', 'automation']
print(''.join(test))

15. Reverse strings or lists

# list reverse
lst = [1,3,5]
lst.reverse()
print(lst)
# iterator reverse
for e in reversed([1,3,5]):
    print(e)
# slice reverse string
print('Test Python'[::-1])

16. Use enumerate for indexed loops

testlist = [10,20,30]
for i, value in enumerate(testlist):
    print(i, ':', value)

17. Simple enum using class attributes

class Shapes:
    Circle, Square, Triangle, Quadrangle = range(4)
print(Shapes.Circle)
print(Shapes.Square)

18. Return multiple values from a function

def x():
    return 1,2,3,4
a,b,c,d = x()
print(a,b,c,d)

19. Unpack arguments with * and **

def test(x,y,z):
    print(x,y,z)

testDict = {'x':1,'y':2,'z':3}
testList = [10,20,30]

test(*testDict)
test(**testDict)
test(*testList)

20. Store simple operations in a dictionary

stdcalc = {'sum': lambda x,y: x+y,
           'subtract': lambda x,y: x-y}
print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))

21. One‑liner factorial

# Python 2
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
# Python 3
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)

22. Most frequent element in a list

test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))

23. Reset recursion limit

import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(1001)
print(sys.getrecursionlimit())

24. Check object memory usage

import sys
x = 1
print(sys.getsizeof(x))  # 24 in Python 2, 28 in Python 3

25. Reduce memory with __slots__

class FileSystem1(object):
    __slots__ = ['files','folders','devices']
    def __init__(self, files, folders, devices):
        self.files = files
        self.folders = folders
        self.devices = devices
print(sys.getsizeof(FileSystem1))

26. Lambda as a print‑like function

lprint = lambda *args: sys.stdout.write(" ".join(map(str,args)))
lprint('python','tips',1000,1001)

27. Build a dictionary from two related sequences

t1 = (1,2,3)
t2 = (10,20,30)
print(dict(zip(t1,t2)))

28. One‑liner prefix/suffix checks

print('http://www.google.com'.startswith(('http://','https://')))
print('http://www.google.co.uk'.endswith(('.com','.co.uk')))

29. Create a flat list without explicit loops

import itertools
nested = [[-1,-2],[30,40],[25,35]]
print(list(itertools.chain.from_iterable(nested)))

30. Simulate a switch‑case with a dictionary

def xswitch(x):
    return xswitch._system_dict.get(x)
xswitch._system_dict = {'files':10,'folders':5,'devices':2}
print(xswitch('devices'))

These tips aim to improve Python code readability, performance, and developer productivity.

fundamentalscode snippetsProgramming TipsPython Tricks
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.