This article is participating in Python Theme Month. See the link to the event for more details

If you ask any Python programmer to talk about the advantages of Python, he will cite brevity and high readability as the most influential advantages. In this Python tutorial, we introduce a number of basic Python tutorials and tricks that will validate both of these points.

I’ve been collecting these useful shortcuts since I started using Python. What could be more rewarding than sharing what we know that can benefit others?

So today, I’m here with some basic Python tutorials and tips. All of these tips can help you reduce code and optimize execution. In addition, you can easily use them in real-time projects while working on regular tasks.

directory

1. Exchange two numbers locally 2. Compare operator links 3. 4. Use a multi-line string. 5. Store the list elements in a new variable. 6. Print the path of the module file to be imported. 7. Use the interactive _ operator. 8. Dictionary/set understanding. 9. Debug the script. 10. Configure file sharing. 11. Examine objects in Python. 12. Simplify if statements. 13. Detect the Python version at runtime. 14. Combine multiple strings. 15. Four ways to reverse string/list. 16. Play enumerations. Use enumerations in Python. Return multiple values from a function. 19. Unpack function parameters using the splat operator. 20. Use a dictionary to store switches. 21. Calculate the factorial of any number in a row. 22. Look for the most frequent value in the list. 23. Reset the recursive limit. 24. Check the memory usage of the object. 25. Use slots to reduce memory overhead. 26.Lambda mimics the printing function. 27. Create a dictionary from two related sequences. 28. Multiple prefixes in an online search string. 29. Create a unified list without any loops. Implement true switch-case statements in Python. Summary – Python tips and tricks

Tip 1 swap two numbers in place

Python provides an intuitive way to assign and exchange values on a single 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)
Copy the code

The assignment on the right is to sow a new tuple. The one on the left immediately unpacks that (unreferenced) tuple into the names and .

After the allocation is complete, the new tuple is dereferenced and marked for garbage collection. The exchange of variables also happens at the end.

Return to the directory


Tip 2: Compare operator links.

Aggregation of comparison operators is another technique that can sometimes come in handy.

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

# True 

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

# False
Copy the code

Return to the directory


Tip 3: Use ternary operators for conditional assignment.

Ternary operators are shortcuts to if-else statements, also known as conditional operators.

[on_true] if [expression] else [on_false]
Copy the code

Here are some examples that you can use to keep your code compact and concise.

The following statement means the same, that is, “if y is 9, assign 10 to x, otherwise assign 20 to x.” We can extend the links to the operators if we want.

x = 10 if (y == 9) else 20
Copy the code

Again, we can do the same thing with class objects.

x = (classA if y == 1 else classB)(param1, param2)
Copy the code

In the above example, classA and classB are two classes, and one of the class constructors will be called.

Here’s an example without one. Add conditions to evaluate the minimum 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
Copy the code

We can even use ternary operators 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, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
Copy the code

Return to the directory


Tip 4 Use multi-line strings

The basic approach 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
Copy the code

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
Copy the code

The common problem with the above methods is the lack of proper indentation. If we try to indent, it inserts Spaces into the string.

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 age
Copy the code

Return to the directory


Tip 5 Stores list elements in new variables

We can use a list to initialize a no. The variables. When decompressing the list, the number of variables should not exceed the number. Elements in the list.

testList = [1.2.3]
x, y, z = testList

print(x, y, z)

# - > 1, 2, 3
Copy the code

Return to the directory


Tip 6 Print the file path of the imported module

If you want to know the absolute location of the imported module in your code, use the following tips.

import threading 
import socket

print(threading)
print(socket)

# 1 - < module 'when' from '/ usr/lib/python2.7 / threading py' >
# 2 - < module 'socket' from '/ usr/lib/python2.7 / socket. Py' >
Copy the code

Return to the directory


Tip 7 Use the interactive “_” operator

This is a useful feature that many of us don’t know about.

In the Python console, whenever we test an expression or call a function, the result is sent to the temporary name _ (underscore).

>>> 2 + 1
3
>>> _
3
>>> print _
3
Copy the code

“_” refers to the output of the last expression executed.

Return to the directory


Tip 8 Dictionary/set understanding

Just as we use list derivation, we can also use dictionary/set derivation. They are easy to use and just as effective. Here’s 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 – the only difference between the two statements is <:>. Also, to run the above code in Python3, replace with.

Return to the directory


Tip 9 debug scripts

Breakpoints can be set in a Python script with the help of a module. Follow the following example.

import pdb
pdb.set_trace()
Copy the code

We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s very convenient.

Return to the directory


Tip 10 Configure file sharing

Python allows you to run an HTTP server, which you can use to share files from the server root. Here are the commands to start the server.

Python 2

python -m SimpleHTTPServer
Copy the code

Python 3

python3 -m http.server
Copy the code

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.

Return to the directory


Tip 11 Examine objects in Python

We can examine objects in Python by calling the dir() method. This is 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

Return to the directory


Tip 12: Simplify if statements

To validate multiple values, we can do this in the following manner.

if m in [1.3.5.7] :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]’ as the ‘in’ operator because ‘set’ can access each element through O(1).

Return to the directory


Tip 13: Detect the Python version at runtime

Sometimes, we may not want to execute our program if the current Python engine is running below the supported version. To do this, you can use the following code 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") orsys.hexversion ! =50660080:
    print("Sorry, you aren't running on Python 3.5\n")
    print("Both 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

Alternatively, you can replace sys.hexversion! With sys.version_info >= (3, 5) in the code above. = 50660080. This is the advice of an informed reader.

Output when run on Python 2.7.

Python 2.710. (default, Jul 14 2015.19:46:27)
[GCC 4.82.] on linux
   
Sorry, you arenNot running on Python 3.5 Please upgrade to 3.5.Copy the code

Output when run on Python 3.5.

Python 3.51. (default, Dec 2015.13: 05:11)
[GCC 4.82.] on linux
   
Current Python version:  3.52. (default, Aug 22 2016.21:11:05) 
[GCC 5.3. 0]
Copy the code

Return to the directory


Tip 14 Combine multiple strings

If you want to connect all the available tags in the list, see the following example.

>>> test = ['I'.'Like'.'Python'.'automation']
Copy the code

Now, let’s create a string from the elements in the list given above.

>>> print ' '.join(test)
Copy the code

Return to the directory


Tip 15 Four ways to reverse a string/list

Reverse the list itself

testList = [1.3.5]
testList.reverse()
print(testList)

# - > [5, 3, 1)
Copy the code

Reverse as you iterate through the loop

for element in reversed([1.3.5) :print(element)

# 1 - > 5
# 2 - > 3
# 3 - > 1
Copy the code

Invert a string

"Test Python"[: : -1]
Copy the code

This makes the output “nohtyP tseT”

Use slices to reverse the list

[1.3.5] [: : -1]
Copy the code

The above command will print [5, 3, 1].

Return to the directory


Tip 16 Playing enumerations

Using the enumerator, it is easy to find the 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:30
Copy the code

Return to the directory


Tip 17 Use enumerations in Python.

We can create an enumeration definition using the following methods.

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
Copy the code

Return to the directory


Tip 18 Returns multiple values from a function.

Not many programming languages support this feature. However, functions in Python do return multiple values.

See the following example to see it in action.

# 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)
Copy the code

#-> 1 2 3 4

Return to the directory


Tip 19 Unpack function arguments using the splat operator.

The SPLat operator provides an artistic way to unpack parameter lists. 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 to 30
Copy the code

Return to the directory


Tip 20 Use a dictionary to store switches.

We can make 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
Copy the code

Return to the directory


Technique 21 Calculates the factorial of any number in a row.

Python 2.x.

result = (lambda k: reduce(int.__mul__, range(1,k+1),1(a))3)
print(result)
# - > 6
Copy the code

Python 3.x.

import functools
result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1(a))3)
print(result)
Copy the code

#-> 6


Tip 22 Look for the most frequent value in the list.

test = [1.2.3.4.2.2.3.1.4.4.4]
print(max(set(test), key=test.count))

# - > 4
Copy the code

Return to the directory


Tip 23 Reset recursive limits.

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
Copy the code

Apply these techniques only when necessary.

Return to the directory


Tip 24 Check the memory usage of the object.

In Python 2.7, 32-bit integers consume 24 bytes, while in Python 3.5 they consume 28 bytes. To verify memory usage, we can call methods.

Python 2.7.

import sys
x=1
print(sys.getsizeof(x))

# - > 24
Copy the code

Python 3.5.

import sys
x=1
print(sys.getsizeof(x))

# - > 28
Copy the code

Return to the directory


Tip 25: Use __slots__ to reduce memory overhead.

Have you observed that your Python application consumes a lot of resources, especially memory? This is a trick to use the <__slots__> class variable to reduce memory overhead 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
Copy the code

Obviously, you can see some savings in memory usage in the results. But when a class’s memory overhead is unnecessarily large, you should use __slots__. Do this only after the application is parsed. Otherwise, you’ll make the code difficult to change with no real benefit.

Return to the directory


Tip 26 Lambda mimics the printing function.

import sys
lprint=lambda *args:sys.stdout.write("".join(map(str,args)))
lprint("python"."tips".1000.1001)

#-> python tips 1000 1001
Copy the code

Return to the directory


Tip 27 Create 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

Return to the directory


Tip 28 Search for multiple prefixes in an online string.

print("http://www.baidu.com".startswith(("http://"."https://")))
print("https://juejin.cn".endswith((".com".".cn")))

#1-> True
#2-> True
Copy the code

Return to the directory


Tip # 29 Form a unified list without using any loops.

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

If you have an input list that contains nested lists or tuples as elements, use the following tips. 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]
Copy the code

Another simpler way to unify lists containing lists and tuples is to use Python’s < more_itertools > package. It doesn’t need to loop. Simply run < 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]
Copy the code

Return to the directory


Tip 30: Implement true switch-case statements in Python.

This is code that uses dictionaries to mimic the Switch-case construct.

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
Copy the code

Return to the directory


Summary – Python tips and tricks

We hope that the basic Python tips and tricks given above will help you get things done quickly and efficiently. You can use them for your jobs and projects.

I’ve been writing a tech blog for a long time, and this is one of my tips. Hope you like it! Here is a summary of all my original and work source code:

Making, Gitee

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support