Python is a simple and flexible programming language, and there are many ways to implement a small function.

However, different implementations can be quite different.

There is a huge difference between an ordinary implementation and a good one in terms of memory footprint and execution efficiency.

In this article, I will introduce you to 8 Python programming tips to help you write more elegant Python code.

1. Enumerate () instead of range(len())

Problem: Iterate over a list and set values less than 0 to 0.

Traversing a list is a common operation in the development process.

Most Python developers are used to using the range(len()) syntax, which is introduced in many tutorials and books, and is therefore the default way for many students to iterate over lists.

Using the enumerate() function is a better choice for traversing lists because it can fetch both the index and the current item, which is useful in many scenarios. Using range(len()) doesn’t work with both the index and the current item.

Here’s a comparison of the two ways:

data = [1.2, -3, -4]

# range(len())
for i in range(len(data)):
    if data[i] < 0:
        data[i] = 0

# enumerate()
data = [1.2, -3, -4]
for idx, num in enumerate(data):
    if num < 0:
        data[idx] = 0
Copy the code

2. List expressions replace for loops

Problem: find the square of ownership in a list.

The more common for loop looks like this:

squares = []
for i in range(10):
    squares.append(i*i)
Copy the code

With a list expression, it looks like this:

squares = [i*i for i in range(10)]
Copy the code

One line of code can do what three lines of code would do in the for loop.

List expressions are very powerful and can also be used in conjunction with conditional statements.

However, don’t overuse list expressions. Because it makes code simpler and increases the cost of reading comprehension. Therefore, it is not recommended to use list expressions in complex statements.

3. Run the set command to remove the load

Problem: Deduplicating an element in a list.

When seeing this problem, some students will think of many complicated methods, traversal, dictionary….

List elements can be de-duplicated with a single line of code called set.

Because a set is an unordered collection, it automatically removes duplicate elements from the list.

my_list = [1.2.3.4.5.6.7.7.7]
set(my_list)
# set([1, 2, 3, 4, 5, 6, 7])
Copy the code

4. Use generators to save memory

Question: How can I save memory if there are 10,000 elements in the list?

If there are few elements, using lists is a good choice. If there are too many elements, the list becomes very memory intensive.

The visual explanation generator, as its name suggests, generates one element at a time, and as you call it, it increments the next element. It’s a very memory saving function if you don’t call it.

So just to compare that,

import sys

my_list = [i for i in range(10000)]
print(sys.getsizeof(my_list), 'bytes') # 87616 bytes

my_gen = (i for i in range(10000))
print(sys.getsizeof(my_gen), 'bytes') # 128 bytes
Copy the code

As you can see, for the same 10,000 elements, the memory footprint of using lists is 684.5 times that of using generators.

Code word is not easy nonsense two sentences: there is a need to learn information or technical problems exchange”Click on the”

5. Use.get() and.setdefault() to access the dictionary

Problem: Accessing values in a dictionary.

When we access the dictionary through key, if the k-v value is not present in the dictionary, it will report an error, terminate the program, and return KeyError.

So it’s better to use the.get() method in the dictionary. This also returns the value of the key, but it does not raise a key error if the key is not available. Instead, it returns the default value we specified, or None if we didn’t specify it.

my_dict = {'item': 'football'.'price': 10.00}
price = my_dict['count'] # KeyError!

# better:
price = my_dict.get('count'.0) # optional default value
Copy the code

Counting with a dictionary is a common operation.

In this process, you need to determine whether the key is present in the dictionary and assign it to the default value, whereas.setdefault() can be used to set the default value directly to the dictionary.

6. Count using collections.counter

Problem: Count the number of occurrences of elements in a list field and filter the most frequent occurrences.

In the project development, counting, statistical frequency, is often encountered problems.

Python’s standard module, collections.Counter, provides many useful and powerful technical methods that can do a lot of complicated logic with a single line of code.

For example, if you want to count the most frequent elements in a list, you can do this:

from collections import Counter

my_list = [10.10.10.5.5.2.9.9.9.9.9.9]
counter = Counter(my_list)

most_common = counter.most_common(2)
print(most_common) # [(9, 6), (10, 3)]
print(most_common[0]) # (9, 6)
print(most_common[0] [0]) # 9
Copy the code

7. Use ** to merge fields

Problem: You are given two dictionaries to merge elements into the same field

Instead of going through two layers to read the elements in the dictionary and then merging them into the same dictionary, a simple double star ** does the trick.

This syntax is new since Python3.5 and was not available before Python3.5.

Here’s an example:

d1 = {'name': 'Alex'.'age': 25}
d2 = {'name': 'Alex'.'city': 'New York'}
merged_dict = {**d1, **d2}
print(merged_dict)
# {'name': 'Alex', 'age': 25, 'city': 'New York'}
Copy the code

8. Simplify conditional statements with if x in list

Problem: Determine if it is equal to the value of an element in the list.

Students who are accustomed to C/C++, Java and other programming languages for development will choose == or! When they encounter conditional statements. = to judge.

If you have a lot of criteria, you need to write a very long statement, for example,

colors = ["red"."green"."blue"]

c = "red"

if c == "red" or c == "green" or c == "blue":
    print("is main color")
Copy the code

In Python, however, conditional statements are greatly simplified and can be solved using in, which is a short line of code.

colors = ["red"."green"."blue"]

c = "red"

if c in colors:
    print("is main color")
Copy the code

As a Python developer, I spent three days to compile a set of Python learning tutorials, from the most basic Python scripts to Web development, crawlers, data analysis, data visualization, machine learning, etc. These materials can be “clicked” by the friends who want them