Welcome! If you’re looking for super cool Python tips and coding snippets to reuse, you’ve come to the right place. Discover the 30 hottest Python tips and tricks, perfect for coders at both basic and advanced levels. Enjoy these ready-to-use suggestions to enhance your Python skills effortlessly.
Python Programming Tips and Tricks
Python coding skills are in high demand, especially since after pandemic started. To thrive in this competitive landscape, you need to know some tricks that can help you write efficient code and save time.
Set-1 of Basic-level Coding Tips
By following our tips, you can write more efficient code that will run faster and save you time.
1. Swap two numbers using the in-place swapping technique.
Python provides an intuitive way to do assignments and swap in one line. Please refer to the below example.
x, y = 10, 20 print(x, y) x, y = y, x print(x, y) #1 (10, 20) #2 (20, 10)
The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <x> and <y>.
Once the assignment follows through, the new tuple gets unreferenced and flagged for garbage collection. And the swapping of variables occurs eventually.
2. Chain multiple comparison operators in a single line of code.
The chaining or aggregation of comparison operators is a cool tip that can make your Python code more concise and easier to read.
# Standard way if x < y and y < z: print("x is less than y and y is less than z") # After chaining the operators if x < y < z: print("x is less than y and y is less than z")
The latter is more concise and easier to read because the three comparisons are chained together.
3. Optimize if-else using the Python ternary operator.
The ternary operator is a shortcut to Python if-else statements and belongs to the class of conditional operators.
# Syntax [on_true] if [expression] else [on_false]
Here are a few examples that you can use to make your code compact and concise.
The below statement is doing the same as it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x”. We can though extend the chaining of operators if required.
# Pseudo code x = 10 if (y == 9) else 20
Likewise, we can do the same for class objects.
# Pseudo code x = (class1 if y == 1 else class2)(param1, param2)
In the above example, class1 and class2 are two classes and one of the class constructors would get called.
Below is one more example with many conditions joining to evaluate the smallest number.
def small(a, b, c): return a if a <= b and a <= c else (b if b <= a and b <= c else c) print(small(1, 0, 1)) print(small(1, 2, 2)) print(small(2, 2, 3)) print(small(5, 4, 3)) #Output #0 #1 #2 #3
We can even use a ternary operator with a list comprehension.
print([m**2 if m > 10 else m**4 for m in range(50)]) #=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
4. Use multi-line strings to increase code readability.
The basic approach to handle multiline strings in Python is by using a backslash to span the string to the next line.
multiStr = "select * from multi_row \ where row_id < 5" print(multiStr) # select * from multi_row where row_id < 5
Another trick is to enclose the string inside a starting and ending triple quote.
multiStr = """select * from multi_row where row_id < 5""" print(multiStr) #select * from multi_row #where row_id < 5
However, the common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.
So the final solution is to split the string into multiple lines and enclose the entire string in parenthesis.
multiStr= ("select * from multi_row " "where row_id < 5 " "order by age") print(multiStr) #select * from multi_row where row_id < 5 order by age
5. Store individual elements of a list into separate variables.
We can use a list to initialize several variables. While unpacking the list, the count of variables shouldn’t exceed the number of elements in the list.
testList = [1,2,3] x, y, z = testList print(x, y, z) #-> 1 2 3
6. Check where your imported Python modules are stored.
If you want to know the absolute location of modules imported in your code, then use the below trick.
import threading import socket print(threading) print(socket) #1 <module 'threading' from '/usr/local/lib/python3.10/threading.py'> #2 <module 'socket' from '/usr/local/lib/python3.10/socket.py'>
7. Check the result of recently executed commands in Python.
It’s a useful feature that not many of us know. In the Python console, whenever we test an expression or call a function, the result is dispatched to a temporary variable, _ (an underscore).
# Note- To be tested in a Python command terminal >>> 2 + 1 3 >>> _ 3 >>> print _ 3
The “_” references the output of the last executed expression.
8. Create dictionaries or sets without writing long and complex code.
Like we use list comprehensions, we can also use dictionary/set comprehensions. They are simple to use and just as effective. Here is an example.
testSet = {i * 2 for i in range(10)} testDict = {i: i * i for i in range(10)} print("#1 ", type(testSet), testSet) print("#2 ", type(testDict), testDict) #1 <class 'set'> {0, 2, 4, 6, 8, 10, 12, 14, 16, 18} #2 <class 'dict'> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Note- There is only a difference of <:> in the two statements.
9. Find and fix bugs in your code by enabling traces.
Sometimes, it gets difficult to identify which part of the code is failing. Python comes with a PDB module that you can use to set breakpoints in your code and isolate the issue. Please follow the below example to enable debugging.
import pdb pdb.set_trace()
You can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s extremely convenient.
10. Start an HTTP server with a one-line Python command.
Python allows running an HTTP server which you can use to share files from the server’s root directory. Below are the commands to start the server.
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server
The above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.
Set-2 of Intermediate-level Coding Tips
As we delve deeper into these Python coding tips and tricks, you’ll find that mastering these techniques can significantly streamline your code and make you a more proficient Python programmer.
11. Inspect the properties of an object in Python.
Let’s explore one of the simplest Python tips to help us inspect objects on the fly by calling the dir() method. Here is the sample code for you to try.
test = [1, 3, 5, 7] print( dir(test) )
# Output # ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
12. Optimize long if statements using 'in'
operator.
To verify multiple values, we can do this in the following manner.
if m in [1,3,5,7]:
instead of:
if m==1 or m==3 or m==5 or m==7:
Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for the ‘in’ operator because ‘set’ can access each element by O(1).
13. Find out the version of Python your code is running on.
Sometimes we may not want to execute our program if the Python engine currently running is less than the supported version. To achieve this, you can use the below coding snippet. It also prints the currently used Python version in a readable format.
import sys #Detect the Python version currently in use. if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: print("Sorry, you aren't running on Python 3.5\n") print("Please upgrade to 3.5.\n") sys.exit(1) #Print Python version in a readable format. print("Current Python version: ", sys.version)
Alternatively, you can usesys.version_info >= (3, 5)
it to replacesys.hexversion!= 50660080
in the above code. It was a suggestion from one of the informed readers.
Output when running on Python 2.7.
# Output 1 Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5 Please upgrade to 3.5.
Output when running on Python 3.5.
# Output 2 Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]
14. Concatenating multiple strings in Python efficiently.
If you want to concatenate all the tokens available in a list, then see the below example.
# Test input test = ['I', 'Like', 'Python', 'automation']
Now, let’s create a single string from the elements in the list given above.
test = ['I', 'Like', 'Python', 'automation'] print( ' '.join(test) ) # Output # I Like Python automation
15. Reverse a string or a list in Python.
In Python, reversing strings or a list is a common task for most programmers while working on different projects. Hence, we are sharing 4 different Python tips that can help you in doing it. Choose any of the below methods that strike you the most.
By the way, if you want a more detailed version of this topic, read it from here: Reverse a list in Python.
#15.1 Reverse the list itself
testList = [1, 3, 5] testList.reverse() print(testList) #-> [5, 3, 1]
#15.2 Reverse while iterating in a loop
for element in reversed([1,3,5]): print(element) #1-> 5 #2-> 3 #3-> 1
#15.3 Reverse a string in line
print( "nohtyP tseT"[::-1] ) # Output # Test Python
#15.4 Reverse a list using slicing
print( [1, 3, 5][::-1] ) # Output # [5, 3, 1]
16. Want to iterate over a list and keep track of the index?
With enumerators, you can easily find an index while you’re inside a loop.
testlist = [10, 20, 30] for i, value in enumerate(testlist): print(i, ': ', value) #1-> 0 : 10 #2-> 1 : 20 #3-> 2 : 30
17. Have you heard about enums in Python?
It is one of the most unheard Python tips and tricks. Let’s explore how you can use them to create named constants and make your code more organized. We can use the following approach to create enum definitions.
class Shapes: Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle) print(Shapes.Square) print(Shapes.Triangle) print(Shapes.Quadrangle) #1-> 0 #2-> 1 #3-> 2 #4-> 3
18. Return multiple values from a function in Python.
Not many programming languages support this feature. However, functions in Python do return multiple values.
Please refer to the below example to see how it works.
# function returning multiple values. def x(): return 1, 2, 3, 4 # Calling the above function. a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4
One of the most important Python tips is to use functions to break down your code into smaller, reusable pieces. This makes your code more readable, maintainable, and testable.
19. Pass multiple arguments to a function in a concise way.
The splat operator offers an artistic way to unpack argument lists. Please refer to the below example for clarity.
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) #1-> x y z #2-> 1 2 3 #3-> 10 20 30
20. Use dictionaries to create a true switch-case statement in Python.
We can make a dictionary to store expressions and imitate the switch case statement in Python.
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } print(stdcalc['sum'](9,3)) print(stdcalc['subtract'](9,3)) #1-> 12 #2-> 6
Set-3 of Python Advanced-level Coding Tips
Python advanced coding tips offer deep insights and proven strategies that can help you take your Python skills to the expert level and write high-performance, scalable, and robust code.
21. Calculate the factorial of any number in just one line of code.
Follow this for more detail: Calculate the factorial of a number in Python
Python 2.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6
Please make sure to use Python 2 to run the above code or you will get the “Not Defined” error.
Python 3.
from functools import reduce result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) # Output # 6
22. Find the most frequent value in a list in Python.
test = [1,2,3,4,2,2,3,1,4,4,4] print(max(set(test), key=test.count)) #-> 4
23. How to reset the recursion limit in Python.
Python restricts the recursion limit to 1000. We can though reset its value.
import sys x=1001 print(sys.getrecursionlimit()) sys.setrecursionlimit(x) print(sys.getrecursionlimit()) #1-> 1000 #2-> 1001
Please apply the above trick only if you need it.
24. Check the memory usage of an object in Python.
In Python 2.7, a 32-bit integer consumes 24 bytes whereas it utilizes 28 bytes in Python 3.5. To verify the memory usage, we can call the <getsizeof> method. Let’s explore one of the unique Python tips to achieve this and make your code more efficient!
In Python 2.7.
import sys x=1 print(sys.getsizeof(x)) #-> 24
In Python 3.5.
import sys x=1 print(sys.getsizeof(x)) #-> 28
25. Reduce the memory overheads of Python classes.
Have you ever observed your Python application consuming a lot of resources, especially memory? Here is one trick using the <__slots__> class variable to reduce memory overhead to some extent. Let’s learn how to use slots and make your Python classes more efficient!
import platform import sys print("Python version:= ", platform.python_version()) class FileSystem(object): def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print("Size without using slot:= ", sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print("Size while using slot:= ", sys.getsizeof( FileSystem1 )) # Output # Python version:= 3.8.10 # Size without using slot:= 1064 # Size while using slot:= 896
You can see from the results that there are savings in memory usage. But you should use __slots__ when the memory overhead of a class is unnecessarily large. Do it only after profiling the application. Otherwise, you’ll make the code difficult to change and with no real benefit.
26. Make a powerful print function using Lambda.
Say goodbye to repetitive print statements! Use lambda functions in Python to create a shortcut that imitates the print function in Python. Save time and streamline your code with this simple yet one of the most powerful Python tips and tricks.
import sys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) lprint("python", "tips",1000,1001) #-> python tips 1000 1001
27. Create dictionaries from sequences in Python.
Two lists are better than one, but why stop there? With the Python zip function, you can easily create a dictionary that pairs up related sequences. Discover the power of combining data into a dictionary and level up your data analysis game.
t1 = (1, 2, 3) t2 = (10, 20, 30) print(dict (zip(t1,t2))) #-> {1: 10, 2: 20, 3: 30}
28. Super quick way to find multiple prefixes in a string.
Searching for multiple prefixes in a string has never been easier. With Python’s in-line search function, you can quickly and efficiently locate all instances of your desired prefixes without having to use cumbersome loops. Say goodbye to manual searching and hello to streamlined code.
print("http://www.google.com".startswith(("http://", "https://"))) print("http://www.google.co.uk".endswith((".com", ".co.uk"))) #1-> True #2-> True
29. Say Goodbye to Loops: How to Form a Unified List in Python!
Are you tired of using loops to combine multiple lists? With this tip, you can streamline your code and save time by learning how to form a unified list in Python without using any loops. Discover how to unleash Python’s iter tools and take your code to the next level.
import itertools test = [[-1, -2], [30, 40], [25, 35]] print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]
If you have an input list with nested lists or tuples as elements, then use the below Python trick. However, the limitation here is that it’s using a for Loop.
def unifylist(l_input, l_target): for it in l_input: if isinstance(it, list): unifylist(it, l_target) elif isinstance(it, tuple): unifylist(list(it), l_target) else: l_target.append(it) return l_target test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]] print(unifylist(test,[])) #Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
Another simpler method to unify the list containing lists and tuples is by using Python’s <more_itertools> package. It doesn’t require looping. Just do a <pip install more_itertools>, if not already have it.
import more_itertools test = [[-1, -2], [1, 2, 3, [4, (5, [6, 7])]], (30, 40), [25, 35]] print(list(more_itertools.collapse(test))) #Output=> [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
30. Alternative Python Switch-Case Statement.
Python may not have a native switch-case statement, but that doesn’t mean you can’t create one. Learn how to implement a true switch-case statement in Python and unlock the full potential of this versatile programming language. Say goodbye to cumbersome if-else statements and hello to streamlined code.
def xswitch(x): return xswitch._system_dict.get(x, None) xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2} print(xswitch('default')) print(xswitch('devices')) #1-> None #2-> 2
Great! You must have gone through all the above Python tips and tricks and saved some of these in your programming arsenal. Here are two more posts that you should consider reading.
More Tips:
10 Python coding tips
12 Python performance tips
20 Python pandas tips
20 Python data analysis tips
Conclusion – 30 Python Tips and Tricks
As we draw toward the end of this tutorial, we hope that the Python knowledge we have imparted has left you spellbound. Armed with these essential Python tips and tricks, you should now be able to tackle your tasks faster and more efficiently.
If you want us to continue writing such tutorials, support us by sharing this post on your social media accounts like Facebook / Twitter. This will encourage us and help us reach more people.
Happy coding,
TechBeamers.