This passage is called “The Zen of Python,” and it lists some of The ideas Python espoused, such as:

Beauty is better than ugliness

Clarity is better than obscurity

Simple is better than complex

Readability is important

Don’t ignore mistakes

In the face of uncertainty, refuse to guess

Doing now is better than not doing at all, but doing it blindly is better than not doing at all

If your implementation is hard to articulate, that’s a bad idea; And vice versa

When you’ve learned the basics and can write some code, you may often feel like your implementation is awkward. Experienced programmers will immediately recognize that your code is written by a beginner. That’s what we always say, there’s not enough pythonic code.

Pythonic, in my opinion, contains two aspects: first, the style of the code conforms to The characteristics of Python, and can make proper use of Python’s “syntactic sugar”; Second, the code is simple and beautiful, high stability, good readability, easy to maintain and modify. The “Zen of Python” is not limited to Python, and many ideas are universal to programming.

For example, to implement traversal access to a list of elements, I’ve seen people write this many times:

for i in range(len(lst)): print(lst[i])
Copy the code

Such students are likely to have prior experience with C/C++ or Java. It’s functionally fine, but it’s not concise enough to be pythonic. A better way to do this:

for i in lst: print(i)
Copy the code


Syntactic sugar is called Syntactic sugar, which does not compromise functionality but makes it easier and more readable. There are many similar examples in Python. Here are a few:

Change the value of two variables.

temp = aa = bb = temp
Copy the code

Pythonic writing:

a, b = b, a
Copy the code

2. Similar uses of unpacking can also implement multiple functions that return values. Common writing:

def func(a, b): result = [b, a]
 return resultr = func(a, b)x = r[0]y = r[1]
Copy the code

Pythonic writing:

def func(a, b): return b, ax, y = func(a, b)
Copy the code

3, read and write files, common writing:

f = open('filename.txt')text = f.read()print(text)f.close()
Copy the code

Pythonic writing:

with open('filename.txt') as f:
 for line in f: print(line)
Copy the code

The advantage of with is that it will help you close the file even if something goes wrong.

4, concatenate string, common writing:

letters = ['h'.'e'.'l'.'l'.'o']s = ' 'for l in letters: s += lprint(s)
Copy the code

Pythonic writing:

print(' '.join(letters))
Copy the code

5. For the previous example of traversing a list, if you wanted to bring an index, you could write:

for i, elem in enumerate(lst): print(i, elem)
Copy the code

Iterating through dictionary entries:

for key, value in dct.items(): print(key, value)
Copy the code

6. Fetch elements greater than 0 from the list to generate a new list. Common writing:

new_lst = []
for i in lst:
 if i > 0: new_lst.append(i)
Copy the code

Pythonic writing:

new_lst = [i for i in lst if i > 0]
Copy the code

This is called List Comprehension, and is a very Pythonic use.

Further, if there is a large amount of data and you are just iterating through the new list without requiring a list object, you can use a generator:

new_lst = (i for i in lst if i > 0)
for i in new_lst: print(i)
Copy the code

This saves resources and improves execution efficiency.

Check whether a value is True, an empty list, or None.

if x == True:
 pass
if len(y) == 0:
 pass
if z == None:
 pass
Copy the code

Pythonic writing:

if x:
 pass
if not y:
 pass
if z is None:
 pass
Copy the code

Select * from key; select * from key;

value = dct[key]
Copy the code

The problem with this is that if the key does not exist, the code will report an error. So you have to add more judgment.

Pythonic writing:

value = dct.get(key, 0)
Copy the code

Instead of using the get method, you get None if it doesn’t exist, or the default value specified (0 in this case).

Due to space limitations, the above are just some representative examples. But everything has to be done in moderation, and being overly pythonic can cause code to become less readable. For example, some people like to write many functions in a single statement, which is not Pythonic. Therefore, we need to have some design principles, but we don’t have to stick to the specific form, otherwise we will get into a dead end.

So how can learners write more Pythonic code? At the end of the day, it’s a process of experience. Newbies can’t become old ones overnight after reading a book or taking a class, but they can if they stick with it long enough. Here are a few suggestions:

  1. Keep looking. Look at official libraries, great projects, and learn other people’s code. And some great tutorials and experience sharing,
  2. Search more. When you implement a small feature, do a web search to see what others have written and see if it’s better than your own. An example is how to remove duplicate elements from a list. You can do this yourself through a loop, but if you do a search, you’ll know that list(set(x)) is used.
  3. Write more. Don’t worry about efficiency or style before you write a few lines of code. Eventually, you have to write enough code to have that “aha” moment.

Are you new to Python or an experienced driver? A wave of messages?