Make your Python code more Python

Posted by Jewelie on Tue, 22 Feb 2022 10:42:13 +0100

When we first started learning python, we knew the coding style requirements of Python. We can see its specific description by entering import this through Python terminal.

This is the famous "Zen of python". In short, it is to write python compliant code, which is concise, elegant and readable.

Here are some common Python specifications and code styles that you can refer to and learn.


First, let's take a look at the variable naming convention (pep8):

Folder: package name. It is recommended to use only lowercase letters for naming, and underline is not recommended.

Module: lower case or underlined connection, such as module py, et al.

Class: hump type, initial capitalization, direct connection of words.

class ThisIsAClass(object):

Functions: lowercase, separated by underscores

def this_is_a_func():

Variables: lowercase, separated by underscores

this_is_a_variable = 1

**Constant: * * all letters of the constant name are capitalized, and each word is connected by an underscore, such as THIS_IS_A_CONSTANT = 1

Grammatical style

1. Exchange the values of a and b

Methods in other languages:

a = 5
b = 6
temp = a
a = b
b = temp

In python, a more concise method:

a = 5
b = 6
a, b = b, a
print(a, b)
Output: 5

2. Assignment of multiple variables

python can assign values to multiple variables in one line of code at the same time

a,b,c = 2,5,12

3. Merge strings

In the traditional string merging method, because the string object cannot be changed, each modification will produce a new object, which will consume a lot of memory.

list_str = ["hello ", "python", "!"]
result = ""
for i in list_str:

In python, using the join() method is more efficient. Note that the join() method is only applicable to lists, tuples, collections and other types whose elements are strings.

list_str = ["hello ", "python", "!"]
result = "".join(list_str)

Output: hello python!

4. List de duplication

Use the uniqueness of the set to de duplicate the list

a = [1, 2, 3, 1, 2,3 , 1, 3, 2, 4, 1, 3, 4, 5, 6, 5, 4, 4, 3, 6]
lst = list(set(a))

5.if/else ternary operation

Supported ternary operation formats in python:

Result when true if Judgment conditions else Result when false (note that there is no colon)
st = "a Greater than 4" if a>4 else "a Less than or equal to 4"
Output: a Less than or equal to 4


enumerate() is a built-in function of Python. An iteratable object (list, string, etc.) can be formed into an index sequence, and the index and value can be obtained at the same time.

Get list elements and indexes

# General writing
names = ['Bob', 'Alice', 'Guido']
n = len(names)
for i in range(n):
    print(f'{i} {names[i]}')

# Use the enumerate() function
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names):
    print(f'{index}: {value}')
0: Bob
1: Alice
2: Guido

7. Unpacking

Unpacking is called unpacking in English, which is to take out the elements in the container one by one.

Extract the elements of the list / tuple and assign them to different variables

a, b, c = [1,2,3]
print(a, b, c)
Output: 1 2 3

Unpacking operation in function

In a function call, * can unpack tuples or lists into different parameters.

def func(a, b, c, d):
    print(a, b, c, d)

args = [1, 2, 3, 4]
Output: 1 2 3 4

In the function call, * * unpacks a dictionary in the form of key / value to make it an independent keyword parameter.

def func(a, b, c, d):
    print(a, b, c, d)

kwargs = {"a": 1, "b": 2, "c": 3, "d": 4}
Output: 1 2 3 4

8. List derivation

List derivation can quickly generate a list that meets the specified requirements by using data types such as range interval, tuple, list, dictionary and set.

[expression for iteration variable in iteratable object [if conditional expression]]

[if conditional expression] can be omitted.

Generate a list whose elements are [1x1,2x2,3x3... nxn], assuming n = 10

# General method
lst = []
for i in range(1, 11):
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# List derivation
lst = [i*i for i in range(1,11)]
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

There are no even items in the requested sequence

lst = [i*i for i in range(1, 11) if i % 2 != 0]
Output:[1, 9, 25, 49, 81]

9. Use keyword in

  • In: returns True if a value is found in the specified sequence, otherwise False.
  • not in: returns True if no value is found in the specified sequence, otherwise False.

Determine whether the element is in the list

if 1 in number:
    print("1 in number")
if 0 not in number:
    print("0 not in number")

In the for loop, get each item of list, tuple and Dictionary:

list = [2, 3, 4]
for num in list:
    print (num)
dic = {"name": "xiaoming", "age": 18}
for k, v in dic.items():
    print(k, v)

10. Use zip to synchronize multiple lists

The zip() function is a Python built-in function, which can recombine the elements at the corresponding positions in multiple sequences (lists, tuples, dictionaries, collections, strings, etc.) to generate new tuples.

z = zip([1,2,3],[3,4,5])
Output:[(1, 3), (2, 4), (3, 5)]

11. Truth value judgment

When judging whether a variable is True or not, Python has its own unique way. It does not need to write judgment conditions. It only needs to write the object directly after the if or while keyword.

Common cases where the true value is False:

  • Constant: None and False
  • Value: 0, 0.0, 0j
  • Sequence or set is empty: '', (), [], {}, set(), range(0)
# For Boolean objects, this is recommended
x = True
if x:
# This is not recommended
if x == True:

lst = []
# For list objects, this is recommended
if lst:
# This is not recommended
if len(lst) != 0:

For more information on how to write python, please refer to the book effctive python and the code specification requirements of Python's official website .