Follow 👆 the official account and reply 'python' to get zero-based tutorials! Source from the internet, will delete upon request.
If you ask any Python programmer to talk about the advantages of Python, they will cite simplicity and high readability as the most influential advantages. In this Python tutorial, we will introduce many fundamental Python tutorials and tips that will validate these two points.
Since I started using Python, I have been collecting these useful shortcuts. What could be more meaningful than sharing what we know and can benefit others?
So today, I bring you some basic Python tutorials and tips. All these tips can help you reduce code and optimize execution. Moreover, you can easily use them in real projects when dealing with routine tasks.
Tip 1: Swap Two Numbers In Place
Python provides an intuitive way to assign and swap in one line. Please refer to the example below.
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 creates a new tuple. The left side immediately unpacks that (unreferenced) tuple into the names <span><a></span>
and <span><b></span>
.
After the assignment is complete, the new tuple will be dereferenced and marked for garbage collection. The swap of the variables also occurs at the end.
Tip 2: Chaining Comparison Operators
Chaining comparison operators is another trick that can sometimes come in handy.
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
Tip 3: Conditional Assignment Using Ternary Operator
The ternary operator is a shortcut for if-else statements, also known as the conditional operator.
[on_true] if [expression] else [on_false]
Here are some examples that you can use to make your code compact and concise.
The statement below is equivalent to saying, ‘Assign 10 to x if y is 9, otherwise assign 20 to x’. If needed, we can extend the chaining of operators.
x = 10 if (y == 9) else 20
Similarly, we can do the same with class objects.
x = (classA if y == 1 else classB)(param1, param2)
In the above example, classA and classB are two classes, one of whose constructors will be called.
Here’s an example without it. Adding conditions 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 the ternary operator in list comprehensions.
[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]
Tip 4: Using Multi-line Strings
The basic method is to use backslashes derived from the C language.
multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)
# select * from multi_row where row_id < 5
Another trick is to use triple quotes.
multiStr = """select * from multi_row where row_id < 5"""
print(multiStr)
#select * from multi_row #where row_id < 5
The common problem with the above methods is the lack of proper indentation. If we try to indent, it will insert spaces into the string.
So the ultimate 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 age
Tip 5: Store List Elements in New Variables
We can use a list to initialize a number of variables. The number of variables should not exceed the number of elements in the list when unpacking the list.
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
Tip 6: Print the File Path of Imported Modules
If you want to know the absolute location of the modules imported in the code, use the following trick.
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'>
Tip 7: Use Interactive ‘_’ Operator
This is a useful feature that many of us are unaware of.
In the Python console, every time we test an expression or call a function, the result is sent to a temporary name _ (underscore).
>>> 2 + 13
>>> _
>>> print _
‘_’ references the output of the last executed expression.
Tip 8: Dictionary/Set Comprehension
Just like we use list comprehensions, we can also use dictionary/set comprehensions. They are easy to use and equally effective. Here’s an example.
testDict = {i: i * i for i in range(10)}
testSet = {i * 2 for i in range(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}
Note – the only difference in the two statements is the use of <:>. Also, to run the above code in Python3, replace xrange with range.
Tip 9: Debugging Scripts
We can set breakpoints in Python scripts with the help of the pdb module. Follow the example below.
import pdb
pdb.set_trace()
We can specify <pdb.set_trace()> anywhere in the script and set breakpoints there. This is very convenient.
Tip 10: Set Up File Sharing
Python allows you to run an HTTP server, which you can use to share files from the server’s root directory. Here’s the command to start the server.
Python 2
python -m SimpleHTTPServer
Python 3
python3 -m http.server
The above command will start the server on the default port 8000. You can also use a custom port by passing it as the last parameter to the above command.
Tip 11: Check Objects in Python
We can check objects in Python by calling the dir() method. Here’s a simple example.
test = [1, 3, 5, 7]
print(dir(test))
['__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']
Tip 12: Simplifying if Statements
To validate multiple values, we can do it as follows.
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]’ as the ‘in’ operator since ‘set’ can access each element in O(1).
Tip 13: Detect Python Version at Runtime
Sometimes, we may not want to execute our program if the currently running Python engine is below the supported version. For this, you can use the following code snippet. It also prints the current 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 replace sys.hexversion!= 50660080 with sys.version_info >= (3, 5) in the above code. This is a suggestion from an informed reader.
Output when 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.
Output when 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]
Tip 14: Concatenate Multiple Strings
If you want to concatenate all available tags in a list, see the example below.
>>> test = ['I', 'Like', 'Python', 'automation']
Now, let’s create a string from the elements given in the list above.
>>> print ''.join(test)
Tip 15: Four Ways to Reverse a String/List
Reversing the List Itself
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
Reverse While Iterating in a Loop
for element in reversed([1,3,5]):
print(element)
#1-> 5
#2-> 3
#3-> 1
Reverse a String
"Test Python"[::-1]
This produces the output ‘nohtyP tseT’
Using Slicing to Reverse a List
[1, 3, 5][::-1]
The command above will output [5, 3, 1].
Tip 16: Play with Enumerate
Using an enumerator makes it easy to find the index in a loop.
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value)
#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
Tip 17: Use Enum in Python
We can create an enum definition using the following method.
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
Tip 18: Return Multiple Values from a Function
Not many programming languages support this feature. However, functions in Python can indeed return multiple values.
Please refer to the following 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
Tip 19: Unpacking Function Parameters Using Splat Operator
The splat operator provides an elegant way to unpack a list of parameters. 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 30
Tip 20: Use Dictionary to Store Switch
We can create 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))
#1-> 12
#2-> 6
Tip 21: Calculate Factorial of Any Number in One Line
Python 2.x.
result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
Python 3.x.
import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)
print(result)
#-> 6
Tip 22: Find the Most Frequent Value in a List
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))
#-> 4
Tip 23: Reset Recursion Limit
Python limits recursion to 1000. We can reset its value.
import sys
x=1001
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
#1-> 1000
#2-> 1001
Please apply the above tip only when necessary.
Tip 24: Check Memory Usage of an Object
In Python 2.7, a 32-bit integer consumes 24 bytes, while in Python 3.5 it uses 28 bytes. To verify memory usage, we can call the getsizeof() method.
Python 2.7.
import sys
x=1
print(sys.getsizeof(x))
#-> 24
Python 3.5.
import sys
x=1
print(sys.getsizeof(x))
#-> 28
Tip 25: Use __slots__ to Reduce Memory Overhead
Have you noticed that your Python application consumes a lot of resources, especially memory? This is a technique to reduce memory overhead by using <span><__slots__></span>
class variables to some extent.
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):
self.files = files
self.folders = folders
self.devices = devices
print(sys.getsizeof(FileSystem1))
#In Python 3.5
#1-> 1016
#2-> 888
Clearly, you can see from the results that memory usage has been saved. However, when a class’s memory overhead is unnecessarily large, you should use <span>__slots__</span>
. Only do this after analyzing the application. Otherwise, you will make the code hard to change without any real benefit.
Tip 26: Lambda Mimicking Print Function
import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001)
#-> python tips 1000 1001
Tip 27: Create Dictionary from Two Related Sequences
t1 = (1, 2, 3)
t2 = (10, 20, 30)
print(dict (zip(t1,t2)))
#-> {1: 10, 2: 20, 3: 30}
Tip 28: Search for Multiple Prefixes in a String Online
print("http://www.baidu.com".startswith(("http://", "https://")))
print("https://juejin.cn".endswith((".com", ".cn")))
#1-> True
#2-> True
Tip 29: Form a Unified List Without Using Loops
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 containing nested lists or tuples as elements, use the following trick. However, the limitation here is that it uses 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 way to unify a list containing lists and tuples is to use Python’s < more_itertools > package. It does not require loops. Just execute < pip install more_itertools >, if you haven’t already.
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]
Tip 30: Implement a Real Switch-Case Statement in Python
This is code that mimics the switch-case construct using a dictionary.
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
Get the latest Python zero-based learning materials for 2023, reply in the background: Python
If this article helps you, please take 2 seconds to like + share + let more people see this article and help them out of misunderstanding.