search
HomeBackend DevelopmentPython TutorialHow to make your Python code more pythonic?

Pythonic is very pythonic if translated into Chinese. There are many uses of the noun structure "very +" in China, such as: "very girly", "very national football team", "very CCTV", etc. ·

For the sake of simplicity below, we use P to represent the pythonic writing method, and NP to represent the non-pythonic writing method. Of course, this P-NP is not that P-NP.

Why pursue pythonic?

Compared with NP, P’s writing method is concise, clear, and elegant. Most of the time, the execution efficiency is high, and the less code, the less error-prone it is. I think that good programmers should pursue the correctness, simplicity and readability of the code when writing code. This is exactly the spirit of pythonic.

For programmers (such as myself) who have experience in other programming languages ​​and are new to Python, recognizing the pythonic writing method will bring more convenience and efficiency when writing Python code, and the main readers of this article It will also be this group of programmers.

N examples of P and NP will be given below for readers’ reference.


P vs. NP example

Chained comparison

P:

a = 3
b = 1
1 <= b <= a < 10  #True

NP:

a = 3
b = 1
b >= 1 and b <= a and a < 10 #True

P is a grammar that elementary school students can understand, simple and direct Provincial code ~


Truth Test

P:

name = &#39;Tim&#39;
langs = [&#39;AS3&#39;, &#39;Lua&#39;, &#39;C&#39;]
info = {&#39;name&#39;: &#39;Tim&#39;, &#39;sex&#39;: &#39;Male&#39;, &#39;age&#39;:23 }    
  
if name and langs and info:
    print(&#39;All True!&#39;)  #All True!

NP:

if name != &#39;&#39; and len(langs) > 0 and info != {}:
    print(&#39;All True!&#39;) #All True!

In short, the way P is written is to directly judge whether it is true or false for any object without writing judgment conditions. , which can not only ensure correctness, but also reduce the amount of code.


True and false value table (you can save a lot of code if you remember false!)

True False

True False

Any non-empty string Empty string''

Any non-0 number Number 1

P’s writing method is simple, and after testing, it is more efficient.


If used to detect palindromes, it is a sentence of input == input[::-1], how elegant!

Connection of string lists

P:

def reverse_str( s ):
    return s[::-1]

NP:

def reverse_str( s ):
    t = &#39;&#39;
    for x in xrange(len(s)-1,-1,-1):
        t += s[x]
    return t

string.join() is often used to connect strings in the list, compared to NP, P The method is very efficient and error-free.


List sum, maximum, minimum, product

P:

strList = ["Python", "is", "good"]  
  
res =  &#39; &#39;.join(strList) #Python is good

NP:

res = &#39;&#39;
for s in strList:
    res += s + &#39; &#39;
#Python is good
#最后还有个多余空格

After simple testing, in num When the length of List is 10000000 , summing the list on my machine, P takes 0.6s, NP takes 1.3s, nearly twice the difference. So don’t reinvent your own wheel.


List comprehension

P:

numList = [1,2,3,4,5]   
sum = sum(numList)  #sum = 15
maxNum = max(numList) #maxNum = 5
minNum = min(numList) #minNum = 1
from operator import mul
prod = reduce(mul, numList, 1) #prod = 120 默认值传1以防空列表报错

NP:

sum = 0
maxNum = -float(&#39;inf&#39;)
minNum = float(&#39;inf&#39;)
prod = 1
for num in numList:
    if num > maxNum:
        maxNum = num
    if num < minNum:
        minNum = num
    sum += num
    prod *= num
# sum = 15 maxNum = 5 minNum = 1 prod = 120

You see, using the list comprehension of P, building a new list becomes so simple and intuitive!

The default value of the dictionary

P:

l = [x*x for x in range(10) if x % 3 == 0]
#l = [0, 9, 36, 81]

NP:

l = []
for x in range(10):
    if x % 3 == 0:
        l.append(x*x)
#l = [0, 9, 36, 81]

The get(key,default) method of

dict is used to get the value of key in the dictionary, if it does not exist For this key, the key is assigned the default value default.

Compared with NP, P has less if...else..., which is really the first choice for people who hate if...else...!


for...else... statement

P:

dic = {&#39;name&#39;:&#39;Tim&#39;, &#39;age&#39;:23}  
  
dic[&#39;workage&#39;] = dic.get(&#39;workage&#39;,0) + 1
#dic = {&#39;age&#39;: 23, &#39;workage&#39;: 1, &#39;name&#39;: &#39;Tim&#39;}

NP:

if &#39;workage&#39; in dic:
    dic[&#39;workage&#39;] += 1
else:
    dic[&#39;workage&#39;] = 1
#dic = {&#39;age&#39;: 23, &#39;workage&#39;: 1, &#39;name&#39;: &#39;Tim&#39;}

The else part of

for...else... is used to handle the else part that is not interrupted from the for loop Condition. With it, we don't need to set state variables to check whether the for loop breaks out, which is simple and convenient.

Replacement of ternary symbols

P:

for x in xrange(1,5):
    if x == 5:
        print &#39;find 5&#39;
        break
else:
    print &#39;can not find 5!&#39;
#can not find 5!

NP:

find = False
for x in xrange(1,5):
    if x == 5:
        find = True
        print &#39;find 5&#39;
        break
if not find:
    print &#39;can not find 5!&#39;
#can not find 5!

If you have programming experience in C, you will look for alternatives to A ? B : C . You may find that A and B or C look fine, but b = a > 1 and False or True returns True, when the actual intention should be to return False.

Using b = False if a > 1 else True will return False correctly, so it is an authentic ternary symbol replacement.


Enumerate

P:

a = 3  
  
b = 2 if a > 2 else 1
#b = 2

NP:

if a > 2:
    b = 2
else:
    b = 1
#b = 2

Using enumerate can take out the index and value at one time, avoiding using the index to get the value, and the second parameter of enumerate can Adjust the starting position of the index subscript, the default is 0.

Use zip to create key-value pairs

P:

array = [1, 2, 3, 4, 5]
  
for i, e in enumerate(array,0):
    print i, e
#0 1
#1 2
#2 3
#3 4
#4 5

NP:

for i in xrange(len(array)):
    print i, array[i]
#0 1
#1 2
#2 3
#3 4
#4 5

The zip method returns a tuple, use it to create key-value pairs, simple and clear .

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software