[转]30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS

If you ask any Python programmer to tell about the strengths of Python, he will quote brevity and high readability as the most influencing ones. In this Python tutorial, we’ll cover many essential Python tips and tricks that will authenticate the above two points.

We’ve been collecting these useful shortcuts (tips & tricks) since we started using Python. And what’s best than sharing something we know and which could benefit others as well.

In the past, we’d shared a list of Python programming tips for beginners that aimed to optimize code and reduce coding efforts. And our readers still enjoy reading it.

So today, we’re back with one more set of essential Python tips and tricks. All these tips can help you minify the code and optimize execution. Moreover, you can readily use them in live projects while working on assignments.

Each trick has an example given with a brief explanation. For testing the coding snippets, you can look up these online virtual terminals for Python code execution.

30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS.

TIPS#1. IN-PLACE SWAPPING OF TWO NUMBERS.

Python provides an intuitive way to do assignments and swapping in one line. Please refer the below example.

Python

1

2

3

4

5

6

7

8

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 <a> and <b>.

Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.

TIPS#2. CHAINING OF COMPARISON OPERATORS.

Aggregation of comparison operators is another trick that can come handy at times.

Python

1

2

3

4

5

6

7

8

9

10

n = 10

result = 1 < n < 20

print(result)

# True

result = 1 > n <= 9

print(result)

# False

TIPS#3. USING TERNARY OPERATOR FOR CONDITIONAL ASSIGNMENT.

Ternary operators are a shortcut for an if-else statement and also known as conditional operators.

Syntax for using conditional operator.

Python

1

[on_true] if [expression] else [on_false]

Here are a few examples which you can use to make your code compact and concise.

The below statement is doing the same what 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.

Python

1

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

Likewise, we can do the same for class objects.

Python

1

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

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

Below is one more example with a no. of conditions joining to evaluate the smallest number.

Python

1

2

3

4

5

6

7

8

9

10

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 the list comprehension.

Python

1

2

3

[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]

TIPS#4. MULTI-LINE STRINGS.

The basic approach is to use backslashes which derive itself from C language.

Python

1

2

3

4

5

multiStr = "select * from multi_row \

where row_id < 5"

print(multiStr)

# select * from multi_row where row_id < 5

One more trick is to use the triple-quotes.

Python

1

2

3

4

5

6

multiStr = """select * from multi_row

where row_id < 5"""

print(multiStr)

#select * from multi_row

#where row_id < 5

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 multi lines and enclose the entire string in parenthesis.

Python

1

2

3

4

5

6

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

TIPS#5. STORING ELEMENTS OF A LIST INTO NEW VARIABLES.

We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.

Python

1

2

3

4

5

6

testList = [1,2,3]

x, y, z = testList

print(x, y, z)

#-> 1 2 3

TIPS#6. PRINTING THE FILE PATH OF IMPORTED MODULES.

If you want to know the absolute location of modules imported in your code, then use the below trick.

Python

1

2

3

4

5

6

7

8

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‘>

TIPS#7. INTERACTIVE “_”.

It’s a useful feature which not many of us are aware.

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

Python

1

2

3

4

5

6

>>> 2 + 1

3

>>> _

3

>>> print _

3

The “_” references to the output of the last executed expression.

TIPS#8. DICTIONARY/SET COMPREHENSIONS.

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.

Python

1

2

3

4

5

6

7

8

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}

Note- There is only a difference of <:> in the two statements. Also, to run the above code in Python3, replace <xrange> with <range>.

TIPS#9. DEBUGGING SCRIPTS.

We can set breakpoints in our Python script with the help of the <pdb> module. Please follow the below example.

Python

1

2

import pdb

pdb.set_trace()

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

TIPS#10. SETUP FILE SHARING.

Python allows running an HTTP server which you can use to share files from the server root directory. Below are the commands to start the server.

# PYTHON 2

Shell

1

python -m SimpleHTTPServer

# PYTHON 3

Shell

1

python3 -m http.server

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.

TIPS#11. INSPECT AN OBJECT IN PYTHON.

We can inspect objects in Python by calling the dir() method. Here is a simple example.

Python

1

2

test = [1, 3, 5, 7]

print( dir(test) )

Shell

1

[‘__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‘]

TIPS#12. SIMPLIFY IF STATEMENT.

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

Python

1

if m in [1,3,5,7]:

instead of:

Python

1

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 ‘in’ operator because ‘set’ can access each element by O(1).

TIPS#13. DETECT PYTHON VERSION AT RUNTIME.

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.

Python

1

2

3

4

5

6

7

8

9

10

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 use sys.version_info >= (3, 5) to replace sys.hexversion != 50660080 in the above code. It was a suggestion from one of the informed reader.

Output when running on Python 2.7.

Shell

1

2

3

4

5

6

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

1

2

3

4

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]

TIPS#14. COMBINING MULTIPLE STRINGS.

If you want to concatenate all the tokens available in a list, then see the below example.

Python

1

>>> test = [‘I‘, ‘Like‘, ‘Python‘, ‘automation‘]

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

Python

1

>>> print ‘‘.join(test)

TIPS#15. VERSATILE REVERSE MECHANISM.

# REVERSE THE LIST ITSELF.

Python

1

2

3

4

5

testList = [1, 3, 5]

testList.reverse()

print(testList)

#-> [5, 3, 1]

# REVERSE WHILE ITERATING IN A LOOP.

Python

1

2

3

4

5

for element in reversed([1,3,5]): print(element)

#1-> 5

#2-> 3

#3-> 1

# REVERSE A STRING IN LINE.

Python

1

"Test Python"[::-1]

This gives the output as ”nohtyP tseT”

# REVERSE A LIST USING SLICING.

Python

1

[1, 3, 5][::-1]

The above command will give the output as [5, 3, 1].

TIPS#16. PLAY WITH ENUMERATION.

With enumerators, it’s easy to find an index while you’re inside a loop.

Python

1

2

3

4

5

6

7

testlist = [10, 20, 30]

for i, value in enumerate(testlist):

print(i, ‘: ‘, value)

#1-> 0 : 10

#2-> 1 : 20

#3-> 2 : 30

TIPS#17. USING ENUMS IN PYTHON.

We can use the following approach to create enum definitions.

Python

1

2

3

4

5

6

7

8

9

10

11

12

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

TIPS#18. RETURNING MULTIPLE VALUES FROM FUNCTIONS.

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

Please refer the below example to see it working.

Python

1

2

3

4

5

6

7

8

9

10

# 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

TIPS#19. UNPACK FUNCTION ARGUMENTS USING SPLAT OPERATOR.

The splat operator offers an artistic way to unpack arguments lists. Please refer the below example for clarity.

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

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

TIPS#20. USE A DICTIONARY TO STORE A SWITCH.

We can make a dictionary store expressions.

Python

1

2

3

4

5

6

7

8

9

10

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

TIPS#21. CALCULATE THE FACTORIAL OF ANY NUMBER IN ONE LINE.

PYTHON 2.X.

Python

1

2

3

result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3)

print(result)

#-> 6

PYTHON 3.X.

Python

1

2

3

4

5

import functools

result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3)

print(result)

#-> 6

TIPS#22. FIND THE MOST FREQUENT ELEMENT IN A LIST.

Python

1

2

3

4

test = [1,2,3,4,2,2,3,1,4,4,4]

print(max(set(test), key=test.count))

#-> 4

TIPS#23. RESETTING THE RECURSION LIMIT.

Python restricts recursion limit to 1000. We can though reset its value.

Python

1

2

3

4

5

6

7

8

9

10

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.

TIPS#24. CHECK THE MEMORY USAGE OF AN OBJECT.

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.

IN PYTHON 2.7.

Python

1

2

3

4

5

import sys

x=1

print(sys.getsizeof(x))

#-> 24

IN PYTHON 3.5.

Python

1

2

3

4

5

import sys

x=1

print(sys.getsizeof(x))

#-> 28

TIPS#25. USE __SLOTS__ TO REDUCE MEMORY OVERHEADS.

Have you ever observed your Python application consuming a lot of resources especially memory? Here is one trick which uses <__slots__> class variable to reduce memory overhead to some extent.

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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 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.

TIPS#26. USING LAMBDA TO HANDLE PRINTING.

Python

1

2

3

4

5

import sys

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

lprint("python", "tips",1000,1001)

#-> python tips 1000 1001

TIPS#27. CREATE DICTIONARY FROM TWO RELATED SEQUENCES.

Python

1

2

3

4

5

6

t1 = (1, 2, 3)

t2 = (10, 20, 30)

print(dict (zip(t1,t2)))

#-> {1: 10, 2: 20, 3: 30}

TIPS#28. IN LINE SEARCH FOR MULTIPLE PREFIXES IN A STRING.

Python

1

2

3

4

5

print("http://www.google.com".startswith(("http://", "https://")))

print("http://www.google.co.uk".endswith((".com", ".co.uk")))

#1-> True

#2-> True

TIPS#29. FORM A UNIFIED LIST WITHOUT USING ANY LOOPS.

Python

1

2

3

4

5

import itertools

test = [[-1, -2], [30, 40], [25, 35]]

print(list(itertools.chain.from_iterable(test)))

#-> [-1, -2, 30, 40, 25, 35]

TIPS#30. IMPLEMENTING A TRUE SWITCH-CASE STATEMENT IN PYTHON.

Here is the code that uses a dictionary to imitate a switch-case construct.

Python

1

2

3

4

5

6

7

8

9

10

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

SUMMARY – ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS.

We wish the essential Python tips and tricks given above would help you do the tasks quickly & efficiently. And you could use them for your assignments and projects.

Listening to your feedback makes us do better so share it.

You can even ask us to write on a topic of your choice. We’ll add it to our writing roadmap.

Lastly, if you’d enjoyed the post, then please care to share it with friends and on social media.

Keep Learning,

TechBeamers.

SHARING IS BLISS.

时间: 2024-12-24 13:23:39

[转]30 ESSENTIAL PYTHON TIPS AND TRICKS FOR PROGRAMMERS的相关文章

Matlab tips and tricks

matlab tips and tricks and ... page overview: I created this page as a vectorization helper but it grew to become my annotated Matlab reading cache. In order to motivate the DSP people out there, I am showing below how one can apply a window and scal

[Python Tips]如何找出Python list中有重复的项

如果一个Python list中有很多重复的项,如何有效地找到多少重复的项呢? 可以使用collection的Counter方法.. >>> from collections import Counter >>> Counter([11,22,11,44,22,33]) Counter({11: 2, 22: 2, 33: 1, 44: 1}) [Python Tips]如何找出Python list中有重复的项,布布扣,bubuko.com

(转) How to Train a GAN? Tips and tricks to make GANs work

How to Train a GAN? Tips and tricks to make GANs work 转自:https://github.com/soumith/ganhacks While research in Generative Adversarial Networks (GANs) continues to improve the fundamental stability of these models, we use a bunch of tricks to train th

python tips(持续更新)

1. 引用上一层目录 import syssys.path.append('..')import xx 2. python json JSON是一种轻量级的数据交换格式.可以解决数据库中文存储问题,对象序列化问题,等等. import json encodedjson = json.dumps(obj) decodejson = json.loads(encodedjson) 非常简单. 3. 静态方法 在函数前面@staticmethod @staticmethod def func(): p

Tips and Tricks for Debugging in chrome

Tips and Tricks for Debugging in chrome Pretty print On sources panel ,clicking on the {} on the bottom left hand side. Console.table Display data as a table ,improve readability. Add watch expressions Watching variable changes over time. XHR/fetch b

30个Python常用基础语法分享,希望对你们有帮助!

![**o/upload_images/11897912-4788c44c5646f3e5?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)写在前面 1.冒泡排序 2.计算x的n次方的方法 3.计算aa + bb + c*c + -- 4.计算阶乘 n! 5.列出当前目录下的所有文件和目录名 6.把一个list中所有的字符串变成小写: 7.输出某个路径下的所有文件和文件夹的路径 8.输出某个路径及其子目录下的所有文件路径 9.输出某个路径及其

30个Python物联网小实验5:光线感应灯

30个Python物联网小实验5:光线感应灯 光线传感器 光线变化执行函数 光线状态执行函数 30个Python物联网小实验5:光线感应灯 光线传感器 可以检测周围环境的亮度: 方向性较好,感知特定方向的亮度: 灵敏度可调,用螺丝刀旋转图中蓝色电位器即可: 工作电压:3.3v~5v 数字开关输出:0或1 设有固定螺栓孔,方便安装 光线变化执行函数 接线方法:正极接树莓派的5v正极,负极接树莓派的GND地线,信号输出针脚接GPIO18号口. 上代码: from gpiozero import Li

Some Python Tips

Strings msg = 'line1\n' msg += 'line2\n' msg += 'line3\n' This is inefficient because a new string gets created upon each pass. Use a list and join it together: msg = ['line1', 'line2', 'line3'] '\n'.join(msg) Similarly avoid the + operator on string

[转载]你可能不知道的 30 个 Python 语言的特点技巧

[转载地址:http://www.oschina.net/translate/thirty-python-language-features-and-tricks-you-may-not-know] 从我开始学习Python时我就决定维护一个经常使用的“窍门”列表.不论何时当我看到一段让我觉得“酷,这样也行!”的代码时(在一个例子中.在StackOverflow.在开源码软件中,等等),我会尝试它直到理解它,然后把它添加到列表中.这篇文章是清理过列表的一部分.如果你是一个有经验的Python程序