10 tips to make your Python code more elegant

Posted by adnan1983 on Wed, 05 Jan 2022 08:11:31 +0100

10 tips to improve Python code to make your code more concise and python.

1. Replace range with enumerate

If you need to traverse a list and get indexes and elements at the same time, you may use the syntax of {range(len(data)) in most cases.

For example, we need to traverse a list and find all negative numbers:

Many people learn Python and don't know where to start.

Many people study python，After mastering the basic grammar, I don't know where to find cases.

Many people who have been able to learn cases do not know how to learn more advanced knowledge.

So for these three types of people, I will provide you with a good learning platform, free access to video tutorials, e-books, and the source code of the course!

QQ Group:101677771

data = [1, 3, -5, 7, 9, -11]
for i in range(len(data)):
if data[i] < 0:
print(f"Indexes:{
i}，Element:{
data[i]}")

Output:

Index: 2, element:-5
Index: 5, element:-11

Although this method is effective, it is better to use Python's built-in "enumerate" function, which will return the current index and current element value as a tuple during traversal, so you can directly output the index and value:

data = [1, 3, -5, 7, 9, -11]
for i, v, in enumerate(data):
if v < 0:
print(f"Indexes:{
i}，Element:{
v}")

Output:

Index: 2, element:-5
Index: 5, element:-11

2. Deeply understand the list and replace the for loop

If we want to create a list of square numbers from 0 to 9, a simple method is to create a ， list first, and then ， append ， the square of one number to the end of the list at a time through the ， for ， loop.

squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

But in fact, through list generation, we have a faster method, which can achieve the same function with only one line of code.

squares = [i ** 2 for i in range(10)]
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

3. Sort complex objects through Python's built-in sorted() method

Sorting requirements are common in many scenarios. Iterative objects (lists, tuples, dictionaries) in Python can be sorted. The built-in function {sorted() makes it unnecessary for us to even implement the sorting algorithm ourselves.

data = [1, 3, -5, 7, 9, -11]
sortedData = sorted(data)
print(sortedData)

Output:

[-11, -5, 1, 3, 7, 9]

The sorted () method automatically sorts the list in ascending order. If you want to sort the list in descending order, you can use the parameter ， reverse = True of ， sorted().

The sorted() method is also applicable to tuple type data, but note that the sorted result will return a list.

data = (1, 3, -5, 7, 9, -11)
print(data)
sortedData = sorted(data)
print(sortedData)

Output:

(1, 3, -5, 7, 9, -11)
[-11, -5, 1, 3, 7, 9]

For complex iteratable objects, for example, we can create a list. Each element in the list is a person's dictionary information, and then we sort it according to each person's age.

We can use the {key} parameter of} sorted() to pass in an anonymous function to sort in the way we expect.

data = [{
"name": "Alex", "age": 18},
{
"name": "Band", "age": 21},
{
"name": "Coco", "age": 17}]
sorted_data = sorted(data, key=lambda x: x["age"])
print(sorted_data)

Output:

[{'name': 'Coco', 'age': 17}, {'name': 'Alex', 'age': 18}, {'name': 'Band', 'age': 21}]

4. Use the Set to store unique values

If you have a list with multiple values and need to de duplicate, a good trick is to convert our list into a collection.

Python's set is an unordered data type, and there are no duplicate elements. It also provides operations between different sets, which can find intersection, union and difference sets.

data = [1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 9, 9]
setData = set(data)
print(setData)

Output:

{1, 3, 5, 7, 9}

5. Use the generator to save memory

Sometimes lists are not the best choice. If we have a very large list with 10000 elements, we want to calculate the sum of all elements, although we can use the list. If the amount of data is particularly large, we may encounter memory problems. A better solution is to use the generator.

dataList = [i for i in range(10000)]
print(sum(dataList))
dataGen = (i for i in range(10000))
print(sum(dataGen))

Output:

The list generator has the same syntax as the generator, except that the list generator uses square brackets and the generator uses small brackets.

The generator calculates the elements we need in a way similar to lazy loading, so it generates only one element at a time and only when needed.

We can look at the size of the list and the generator using the {getsize() method of {sys}.

import sys

dataList = [i for i in range(10000)]
print(sys.getsizeof(dataList), "bytes")

dataGen = (i for i in range(10000))
print(sys.getsizeof(dataGen), "bytes")

Output:

85176 bytes
112 bytes

6. Get the element usage in the dictionary get() and set the default value

Suppose we have a dictionary that includes different keys, such as goods and prices. At a point in our code, we want to get the price of goods.

When we use the [] simple access key, if the key is not in the dictionary, the code will report an error and cause a {KeyError.

"name": "Tesla",
"price": 250000
}

Traceback (most recent call last):
File "mian.py", line 5, in <module>
KeyError: 'count'

A better way is to use get() method. At this time, if the key does not exist, it will not raise {KeyError, but return a default value. If we do not specify a default value, it will directly return None. If we specify a default value, it will return the default value we specify.

"name": "Tesla",
"price": 250000
}

Output:

None
0

7. Counter collections Counter

If you want to calculate the number of elements in the list, Python has a very convenient tool.

from collections import Counter

data = [1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 9, 9]
counter = Counter(data)

print(counter)

Output:

Counter({9: 5, 7: 4, 5: 3, 3: 2, 1: 1})

Counter} can count the number of different elements in the list and arrange them in descending order according to the number of occurrences, which is much better than our own calculation.

If you want to know the number of an element, you can access it directly through []. If the element does not exist, it will return 0, and you can also access it through {most_ The common () method returns the top ranked elements.

from collections import Counter

data = [1, 3, 3, 5, 5, 5, 7, 7, 7, 7, 9, 9, 9, 9, 9]
counter = Counter(data)

print(counter)
print(counter)
print(counter.most_common(2))

Output:

4
0
[(9, 5), (7, 4)]

8. Format strings using f-String (for Python 3.6 +)

In my opinion, f-String is the best way to format a string. We only need to write an F before the string, and then we can directly use braces to embed variables or expressions inside the string.

data = {
"name": "Alex", "age": 18}
string = f"I'm {
data['name']} and I am {
data['age']} years old."
print(string)

Output:

I'm Alex and I am 18 years old.

This way is simpler, simpler and faster.

9. Use join() splice string

If we have a list containing different strings, we want to splice all strings together through spaces. Don't go through the for loop one by one and then splice them. A more concise method is through joint() method, which can splice strings using the specified characters.

strings = ["Hello", "World", "!"]
print(" ".join(strings))
print("_".join(strings))

Output:

Hello World !
Hello_World_!

10. Use double asterisk syntax to merge dictionaries (for Python 3.5 +)

If we have two dictionaries and want to merge them into one, we can use the double asterisk * * and brace {} syntax.

info1 = {
"name": "Alex", "age": 18}
info2 = {
"name": "Alex", "city": "Bei Jing"}
info = {
**info1, **info2}
print(info)

Output:

{'name': 'Alex', 'age': 18, 'city': 'Bei Jing'}