If you ask a Python programmer to name the advantages of Python, he or she will say that simplicity and high readability are the most influential advantages. To demonstrate both, in this Python tutorial, we’ll cover a number of basic Python tips and tricks.
We’ve collected these useful shortcuts (tips and tricks) since we started using Python. What could be better than sharing something we know that can benefit others at the same time?
We’ve shared some Python programming tips for beginners in the past aimed at optimizing code and reducing coding effort, and our readers still enjoy reading it.
So today we bring you some other basic Python tips and tricks, all of which can help you compress your code and optimize it. Plus, you can easily use them on real projects in your daily work.
Each technique is provided with an example and a brief explanation, and if you want to test the code snippets, you can take a look at these online virtual Python running terminals.
Two other Must-see Python resources we recently published:
Main ways to optimize Python code in 💡 9
💡 Discover the most common mistakes to avoid when programming
Use the TOC below to quickly navigate through these Python tips and tricks.
30 basic Python tips and tricks for programmers
Tip #1. Switch two numbers in place
Python provides an intuitive way to assign and swap (variable values) in one line of code, as shown in the following example:
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)Copy the code
The right side of the assignment forms a new tuple, and the left side immediately parses (unpack) that (unreferenced) tuple into the variables and .
Once the assignment is complete, the new tuple becomes unreferenced and marked for garbage collection, and the exchange of variables is completed.
Tip #2. The chain comparison operator
Aggregation of comparison operators is another sometimes handy trick:
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# FalseCopy the code
Tip #3. Use the ternary operator for conditional assignment
The ternary operator is a shortcut to the if-else statement, which is the conditional operator:
If [expression] else [return value if expression is false]Copy the code
Here are a few examples you can use to keep your code compact and concise. The following statement says “if y is 9, assign x to 10, otherwise assign x to 20”. We can extend the chain of operations if we want.
x = 10 if (y == 9) else 20Copy the code
Similarly, we can do this with a class:
x = (classA if y == 1 else classB)(param1, param2)Copy the code
In the example above classA and classB are two classes, and the constructor of one class is called.
Here is another example of multiple conditional expressions linked together to compute a minimum:
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 #3Copy the code
We can even use ternary operators in list derivations:
[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]Copy the code
Tip #4. Multi-line strings
The basic way is to use a backslash from C:
multiStr = "select * from multi_row
where row_id < 5"
print(multiStr)
# select * from multi_row where row_id < 5Copy the code
Another trick is to use triple quotation marks:
multiStr = """select * from multi_row
where row_id < 5"""
print(multiStr)
#select * from multi_row
#where row_id < 5Copy the code
The common problem with the above methods is the lack of proper indentation, which would insert Spaces in the string if we tried to indent. So the final solution is to split the string into multiple lines and enclose the entire string in parentheses:
multiStr= ("select * from multi_row " "where row_id < 5 " "order by age") print(multiStr) #select * from multi_row where row_id < 5 order by ageCopy the code
Tip #5. Store list elements in new variables
We can use lists to initialize multiple variables. When parsing a list, the number of variables should not exceed the number of elements in the list:
Print (x, y, z) print(x, y, z) #-> 1 2 3Copy the code
Tip #6. Print the file path to the imported module
If you want to know the absolute path to a module referenced in your code, use the following technique:
import threading import socket print(threading) print(socket) #1- <module 'threading' from '/ usr/lib/python2.7 / threading py' > # 2 - < module 'socket' from '/ usr/lib/python2.7 / socket. Py' >Copy the code
Tip #7. The “_” operator in interactive environments
This is a useful feature that most of us don’t know about. In the Python console, whenever we test an expression or call a method, the result is assigned to a temporary variable: _ (an underscore).
>>> 2 + 1
3
>>> _
3
>>> print _
3Copy the code
The “_” is the output of the last expression executed.
Tip #8. Dictionary/set derivation
Similar to the list derivations we used, we can also use dictionary/set derivations, which are simple and efficient to use. Here is an example:
testDict = {i: i * i for i in xrange(10)} testSet = {i * 2 for i in xrange(10)} print(testSet) print(testDict) #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) # {0:0, 1, 1, 2, 4, 3, 9, 4:16, 5:25, 6:36, 7:49, 8, 64, 9:81}Copy the code
Note: there is only one difference between the two statements. In addition, when running Python3, change
to
.
Tip #9. Debug scripts
We can set breakpoints in Python scripts with the help of the < PDB > module. Here is an example:
import pdb
pdb.set_trace()Copy the code
We can specify < db.set_trace()> anywhere in the script and set a breakpoint there, quite simply.
Tip #10. Turn on file sharing
Python allows you to run an HTTP server to share files from the root path. Here is the command to start the server:
# Python 2
python -m SimpleHTTPServerCopy the code
# Python 3
python3 -m http.serverCopy the code
The above command will start a server on the default port 8000, and you can pass a custom port number as the last parameter in the above command.
Tip #11. Examine objects in Python
We can check objects in Python by calling dir(). Here’s a simple example:
test = [1, 3, 5, 7]
print( dir(test) )Copy the code
['__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']Copy the code
Tip #12. Simplify the if statement
We can verify multiple values as follows:
If m in hc-positie [1] :Copy the code
Instead of:
if m==1 or m==3 or m==5 or m==7:Copy the code
Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for the in operator, because fetching elements in set is an O(1) operation.
Tip #13. Check the Python version at run time
Sometimes we may not want to run our programs when we are running Python below the supported version. To do this, you can use the following code snippet, which also outputs the current Python version in readable form:
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.5n") print("Please upgrade to 3.5.n") sys.exit(1) # print Python version in a readable format. print("Current Python version: ", sys.version)Copy the code
Or you can use sys.version_info >= (3, 5) to replace sys.hexversion in the code above! = 50660080, this is a reader’s suggestion.
Results running on Python 2.7:
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.
Copy the code
Results running on Python 3.5:
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]
Copy the code
Tip #14. Combine multiple strings
If you want to concatenate all the tokens in a list, as in the following example:
>>> test = ['I', 'Like', 'Python', 'automation']Copy the code
Now, let’s create a new string from the list element given above:
>>> print ''.join(test)Copy the code
Tip #15. Four ways to flip strings/lists
# Flip the list itself
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]Copy the code
# Flip and iterate over the output in a loop
For element in reversed([1,3,5]): print(element) #1-> 5 #2-> 3 #3-> 1Copy the code
# One line of code flipping string
"Test Python"[::-1]Copy the code
Output is “nohtyP tseT”
Flip the list using slices
[1, 3, 5] [: : 1]Copy the code
The command above will give the output [5,3,1].
Tip #16. Play with enumerations
Using enumerations makes it easy to find the (current) index in the loop:
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30Copy the code
Tip #17. Use enumerators in Python
We can define enumerators as follows:
class Shapes: Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle) print(Shapes.Square) print(Shapes.Triangle) print(Shapes.Quadrangle) #1-> 0 #3-> 2 #4-> 3Copy the code
Tip #18. Return multiple values from a method
Not many programming languages support this feature, however methods in Python do (can) return multiple values. See the following example to see how this 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 4Copy the code
Tip #19. Use*
Splat operator to unpack function arguments
* The splat operator provides an artful way to unpack a list of arguments. For clarity, see the following example:
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 30Copy the code
Tip #20. Use a dictionary to store selection operations
We can construct a dictionary to store expressions:
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: X-y} print (stdcalc [' sum ']) (9, 3) print (stdcalc [' subtract] (9, 3)) 12 # # 1 - > 2 - > 6Copy the code
Tip #21. One line of code to compute the factorial of any number
Python 2.x.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6Copy the code
Python 3.x.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6Copy the code
Tip #22. Find the most frequent number on the list
,2,3,4,2,2,3,1,4,4,4 test = [1] print (Max (set (test), key = test. The count)) # - > 4Copy the code
Tip #23. Reset recursion limits
Python limits recursion to 1000. We can reset this value:
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001Copy the code
Use the above techniques only when necessary.
Tip #24. Check the memory usage of an object
In Python 2.7, a 32-bit integer takes up 24 bytes; in Python 3.5, 28 bytes. To determine memory usage, we can call the getSizeof method:
In Python 2.7
import sys
x=1
print(sys.getsizeof(x))
#-> 24Copy the code
In Python 3.5
import sys
x=1
print(sys.getsizeof(x))
#-> 28Copy the code
Tip #25. Use__slots__
To reduce memory overhead
Have you noticed that your Python application takes up a lot of resources, especially memory? One trick is to use the __slots__ class variable to reduce memory overhead somewhat.
import sys class FileSystem(object): def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices): Files = files self. Folders = files self. Devices = devices print(sys.getsizeof(FileSystem1)) #In Python 3.5 #1-> 1016 # 2 - > 888Copy the code
Obviously, you can see from the results that there are savings in memory usage, but you should only use __slots__ when a class’s memory overhead is unnecessarily high. Use it only after performance analysis of the application, otherwise you’re just making the code hard to change without real benefit.
In my win10 PYTHon2.7, the above result is:
#In Python 2.7 win10
#1-> 896
#2-> 1016Copy the code
As a result, this comparison is not very convincing. Using __slots__ is mainly used to qualify information about attributes of objects, and it may be less expensive to generate many objects, as can be seen in the Python documentation:
The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a Value for each variable. Space is saved because dict is not created for each instance.
Tip #26. Use lambda to mimic the output method
import sys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) lprint("python", #-> Python tips 1000 1001Copy the code
Tip #27. Build a dictionary from two related sequences
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}Copy the code
Tip #28. One line of code searches for multiple prefixes and suffixes of a string
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
#1-> True
#2-> TrueCopy the code
Tip #29. Don’t use loops to construct a list
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test)))
#-> [-1, -2, 30, 40, 25, 35]Copy the code
Tip #30. Implement a true switch-case statement in Python
The following code uses a dictionary to simulate constructing a switch-case.
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-> 2Copy the code
Conclusion – Basic Python tips and tricks for programmers
We hope that the basic Python tips and tricks mentioned above will help you accomplish tasks quickly and efficiently, and that you can use them in your assignments and projects.
Listening to your feedback makes us better people, so please share your thoughts.
You can even ask us to write about a topic of your choice, and we’ll add it to our writing list. [*]
Finally, if you like this article, please share it with your friends on social media.
Keep learning,