1 Introduction
“Beautiful is better than ugly.”
The above is the first sentence of the famous The Zen of Python, and it is also one of the tenets of aspiring python developers.
So here comes our question: How to write beautiful Python code?
This article focuses on showing you six tips in Python through nine examples to help you write more elegant Python programs in your daily work.
2. Use the product function instead of nested loops
When our programs become complex, it is inevitable to write nested loops. However, nested loops will make the program harder to read and maintain.
Fortunately, we can product()
avoid nested loops in Python with built-in functions.
For example, we have a program that contains 3 levels of nested For
loops:
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
for a in list_a:
for b in list_b:
for c in list_c:
if a + b + c == 2077:
print(a, b, c)
# 70 2000 7
To make the code cleaner, we can use functions from itertools
modules product()
to optimize the code:
from itertools import product
list_a = [1, 2020, 70]
list_b = [2, 4, 7, 2000]
list_c = [3, 70, 7]
for a, b, c in product(list_a, list_b, list_c):
if a + b + c == 2077:
print(a, b, c)
# 70 2000 7
3. The walrus operator: a cute trick in assignment expressions
Since Python 3.8, there has been a walrus operator
new syntax called , which enables value assignments to be passed into expressions.
The Walrus Operator :=
, whose lovely name comes from the eyes and tusks of the walrus.
The syntax of this feature is very simple. For example, if we want to implement the above two lines of code with one line of code, how should we do it?
author = "Zhao"
print(author)
# Zhao
Unfortunately, we cannot directly put assignment expressions into print()
functions. If we try it, there will be a TypeError
:
print(author="Zhao")
# TypeError: 'author' is an invalid keyword argument for print()
Thanks to the walrus operator, we can really do it in one line:
print(author:="Zhao")
# Zhao
4. Ternary operator: write a simple If-Else structure in one line
if-else
Conditional statements are ubiquitous in the programming world. In order to make simple logic easy to express, Python provides us with ternary operators. Simply put, it only allows putting if-else
conditions in one line:
min = a if a < b else b
Obviously, the code above is much cleaner than:
if a<b:
min = a
else:
min = b
5. Define Simple Functions Using Lambda Expressions
If we just want to define a simple function, we probably don't need to use the traditional syntax. lambda
Expressions are often a more elegant option.
For example, the following function is mainly used to realize the function of solving Fibonacci numbers:
def fib(x):
if x<=1:
return x
else:
return fib(x-1) + fib(x-2)
It works perfectly, but the code itself is kind of ugly. Let's write one line of code to implement the same function:
fib = lambda x: x if x <= 1 else fib(x - 1) + fib(x - 2)
6. Using list builds
It's still an understatement that using list comprehensions can make our code more elegant. Because it saves a lot of typing time while keeping the code readable. Very few programming languages can do this.
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = ['Genius' if name.startswith('y') else 'Not Genius' for name in Genius]
print(L1)
# ['Not Genius', 'Not Genius', 'Not Genius', 'Genius']
Feel free to enjoy the elegant program above, and consider how many lines of code we would have written without the list comprehension tricks.
7. Using asterisks to unpack iterables
How to merge a list, a tuple and a set into one list?
The most elegant way is to use the asterisk *
:
A = [1, 2, 3]
B = (4, 5, 6)
C = {
7, 8, 9}
L = [*A, *B, *C]
print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]
As mentioned above, an asterisk can be used as a prefix to an iterable to unpack the corresponding elements.
In addition to unpacking iterables, the asterisk can also be used for destructuring assignments in Python:
a, *mid, b = [1, 2, 3, 4, 5, 6]
print(a, mid, b)
# 1 [2, 3, 4, 5] 6
As shown above, with the help of the asterisk *
, mid
the variable receives the item in the middle as a list.
8. Summary
This article focuses on six tips commonly used in Python, and gives corresponding code examples, which can improve everyone's coding efficiency.
Are you useless?