Home Backend Development Python Tutorial 10 things to note when developing Python

10 things to note when developing Python

Apr 29, 2017 pm 05:05 PM

Below are ten useful tips and tricks in Python. Some of these are common mistakes that beginners make when learning the language.

Note: Assume we are all using Python 3

1. List comprehension

You have a list: bag = [1, 2, 3, 4, 5]

Now you want to double all the elements so that it looks like this: [2, 4, 6, 8, 10]

Most beginners will probably do it like this based on their previous language experience

bag = [1, 2, 3, 4, 5]  
for i in range(len(bag)):  
    bag[i] = bag[i] * 2
Copy after login

​But there is a better way:

bag = [elem * 2 for elem in bag]
Copy after login

Very simple, right? This is called a Python list comprehension.

Click Trey Hunner’s tutorial to see more introduction to list comprehensions.

2. Traverse the list

Continue with the list above.

Avoid doing this if possible:

bag = [1, 2, 3, 4, 5]  
for i in range(len(bag)):  
    print(bag[i])
Copy after login

Instead it should be like this:

bag = [1, 2, 3, 4, 5]  
for i in bag:  
    print(i)
Copy after login

If x is a list, you can iterate over its elements. In most cases you don't need the index of each element, but if you must, use the enumerate function. It looks like below:

bag = [1, 2, 3, 4, 5]  
for index, element in enumerate(bag):  
    print(index, element)
Copy after login

Very intuitive and clear.

3. Element exchange

If you are switching from Java or C language to Python, you may be used to this:

a = 5  
b = 10

# 交换 a 和 b
tmp = a  
a = b  
b = tmp
Copy after login

But Python provides a more natural and better method!

a = 5  
b = 10  
# 交换a 和 b
a, b = b, a
Copy after login

Pretty enough, right?

4. Initialization list

If you want a list of 10 integers 0, you may first think of:

bag = []  
for _ in range(10):  
    bag.append(0)
Copy after login

Let’s try another way:

bag = [0] * 10
Copy after login

Look, how elegant.

Note: If your list contains lists, doing this will produce a shallow copy.

For example:

bag_of_bags = [[0]] * 5 # [[0], [0], [0], [0], [0]]  
bag_of_bags[0][0] = 1 # [[1], [1], [1], [1], [1]]
Copy after login

Oops! All lists are changed, and we only want to change the first list.

Change it:

bag_of_bags = [[0] for _ in range(5)]  
# [[0], [0], [0], [0], [0]]

bag_of_bags[0][0] = 1  
# [[1], [0], [0], [0], [0]]
Copy after login

Also remember:

"Premature optimization is the root of all evil"
Ask yourself, is initializing a list necessary?

5. Construct a string

You will often need to print strings. If there are many variables, avoid the following:

name = "Raymond"  
age = 22  
born_in = "Oakland, CA"  
string = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "."  
print(string)
Copy after login

Um, how messy does this look? You can use a nice and concise method instead, .format.

Do this:

name = "Raymond"  
age = 22  
born_in = "Oakland, CA"  
string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in) 
print(string)
Copy after login

much better!

6. Return tuples

Python allows you to return multiple elements in a function, which makes life easier. However, common errors like this occur when unpacking tuples:

def binary():  
    return 0, 1

result = binary()  
zero = result[0]  
one = result[1]
Copy after login

This is not necessary, you can change it to this:

def binary():  
    return 0, 1

zero, one = binary()
Copy after login

If you need all elements to be returned, use an underscore_:

zero, _ = binary()
Copy after login

It’s so efficient!

7. Access Dicts

You will also often write keys and pairs (keys, values) into dicts.

If you try to access a key that does not exist in the dict, you may want to avoid KeyError errors by doing this:

countr = {}  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
for i in bag:  
    if i in countr:
        countr[i] += 1
    else:
        countr[i] = 1

for i in range(10):  
    if i in countr:
        print("Count of {}: {}".format(i, countr[i]))
    else:
        print("Count of {}: {}".format(i, 0))
Copy after login

However, using get() is a better way.

countr = {}  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
for i in bag:  
    countr[i] = countr.get(i, 0) + 1

for i in range(10):  
    print("Count of {}: {}".format(i, countr.get(i, 0)))
Copy after login

Of course you can also use setdefault instead.

This also uses a simpler but more expensive method:

bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
countr = dict([(num, bag.count(num)) for num in bag])

for i in range(10):  
    print("Count of {}: {}".format(i, countr.get(i, 0)))
Copy after login

You can also use dict derivation.

countr = {num: bag.count(num) for num in bag}
Copy after login

These two methods are expensive because they traverse the list every time count is called.

8 Use library

Just import existing libraries and you can do what you really want.

​Still talking about the previous example, let's build a function to count the number of times a number appears in a list. Well, there is already a library that can do such a thing.

from collections import Counter  
bag = [2, 3, 1, 2, 5, 6, 7, 9, 2, 7]  
countr = Counter(bag)

for i in range(10):  
    print("Count of {}: {}".format(i, countr[i]))
Copy after login

Some reasons for using the library:

  • The code is correct and tested.


  • Their algorithm may be optimal and run faster.


  • Abstractions: They are clear and well-documented, and you can focus on what has not yet been implemented.


  • Finally, it's all there, you don't have to reinvent the wheel.

9. Slicing/stepping in the list

You can specify the start point and stop point, like this list[start:stop:step]. We take out the first 5 elements in the list:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[:5]:  
    print(elem)
Copy after login

This is slicing. We specify the stop point to be 5, and 5 elements will be taken out from the list before stopping.

What to do with the last 5 elements?

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[-5:]:  
    print(elem)
Copy after login

Don’t you understand? -5 means take 5 elements from the end of the list.

If you want to operate on the intervals between elements in the list, you might do this:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for index, elem in enumerate(bag):  
    if index % 2 == 0:
        print(elem)
Copy after login

But you should do it like this:

bag = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
for elem in bag[::2]:  
    print(elem)

# 或者用 ranges
bag = list(range(0,10,2))  
print(bag)
Copy after login

This is the step in the list. list[::2] means traversing the list and taking out an element in two steps.

You can use list[::-1] to do a cool flipping list.

10. Tab key or space key

In the long run, mixing tabs and spaces will cause disaster, and you will see IndentationError: unexpected indent. Whether you choose the tab key or the space bar, you should keep using it throughout your files and projects.

One reason to use spaces instead of tabs is that tabs are not created equal in all editors. Depending on the editor used, tabs may be treated as 2 to 8 spaces.

You can also use spaces to define tabs when writing code. This way you can choose how many spaces to use as tabs. Most Python users use 4 spaces.

English original text: The Python Way: 10 Tips

The above is the detailed content of 10 things to note when developing Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ Development Notes: Avoid Null Pointer Exceptions in C++ Code C++ Development Notes: Avoid Null Pointer Exceptions in C++ Code Nov 22, 2023 pm 02:38 PM

In C++ development, null pointer exception is a common error, which often occurs when the pointer is not initialized or is continued to be used after being released. Null pointer exceptions not only cause program crashes, but may also cause security vulnerabilities, so special attention is required. This article will explain how to avoid null pointer exceptions in C++ code. Initializing pointer variables Pointers in C++ must be initialized before use. If not initialized, the pointer will point to a random memory address, which may cause a Null Pointer Exception. To initialize a pointer, point it to an

Introduction to matters needing attention during the Mingchao test Introduction to matters needing attention during the Mingchao test Mar 13, 2024 pm 08:13 PM

During the Mingchao test, please avoid system upgrades, factory resets, and parts replacement to prevent information loss and abnormal game login. Special reminder: There is no appeal channel during the testing period, so please handle it with caution. Introduction to matters needing attention during the Mingchao test: Do not upgrade the system, restore factory settings, replace equipment components, etc. Notes: 1. Please upgrade the system carefully during the test period to avoid information loss. 2. If the system is updated, it may cause the problem of being unable to log in to the game. 3. At this stage, the appeal channel has not yet been opened. Players are advised to choose whether to upgrade at their own discretion. 4. At the same time, one game account can only be used with one Android device and one PC. 5. It is recommended that you wait until the test is completed before upgrading the mobile phone system or restoring factory settings or replacing the device.

How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? How to start a live broadcast on Douyin for the first time? What should you pay attention to when broadcasting live for the first time? Mar 22, 2024 pm 04:10 PM

With the rise of short video platforms, Douyin has become an indispensable part of many people's daily lives. Live broadcasting on Douyin and interacting with fans are the dreams of many users. So, how do you start a live broadcast on Douyin for the first time? 1. How to start a live broadcast on Douyin for the first time? 1. Preparation To start live broadcast, you first need to ensure that your Douyin account has completed real-name authentication. You can find the real-name authentication tutorial in "Me" -> "Settings" -> "Account and Security" in the Douyin APP. After completing the real-name authentication, you can meet the live broadcast conditions and start live broadcast on the Douyin platform. 2. Apply for live broadcast permission. After meeting the live broadcast conditions, you need to apply for live broadcast permission. Open Douyin APP, click "Me"->"Creator Center"->"Direct

Steps and precautions for using localstorage to store data Steps and precautions for using localstorage to store data Jan 11, 2024 pm 04:51 PM

Steps and precautions for using localStorage to store data This article mainly introduces how to use localStorage to store data and provides relevant code examples. LocalStorage is a way of storing data in the browser that keeps the data local to the user's computer without going through a server. The following are the steps and things to pay attention to when using localStorage to store data. Step 1: Check whether the browser supports LocalStorage

Steps and precautions for installing pip without network Steps and precautions for installing pip without network Jan 18, 2024 am 10:02 AM

Methods and precautions for installing pip in an offline environment. Installing pip becomes a challenge in an offline environment where the network is not smooth. In this article, we will introduce several methods of installing pip in an offline environment and provide specific code examples. Method 1: Use the offline installation package. In an environment that can connect to the Internet, use the following command to download the pip installation package from the official source: pipdownloadpip This command will automatically download pip and its dependent packages from the official source and save it in the current directory. Move the downloaded compressed package to a remote location

Python development experience sharing: how to perform version control and release management Python development experience sharing: how to perform version control and release management Nov 23, 2023 am 08:36 AM

Python development experience sharing: How to carry out version control and release management Introduction: In the Python development process, version control and release management are very important links. Through version control, we can easily track code changes, collaborate on development, resolve conflicts, etc.; and release management can help us organize the deployment, testing and release process of code to ensure the quality and stability of the code. This article will share some experiences and practices in Python development from two aspects: version control and release management. 1. Version control version control

Python Development Notes: Avoid Common Memory Leak Problems Python Development Notes: Avoid Common Memory Leak Problems Nov 22, 2023 pm 01:43 PM

As a high-level programming language, Python is becoming more and more popular among developers due to its advantages of being easy to learn, easy to use, and highly efficient in development. However, due to the way its garbage collection mechanism is implemented, Python is prone to memory leaks when dealing with large amounts of memory. This article will introduce the things you need to pay attention to during Python development from three aspects: common memory leak problems, causes of problems, and methods to avoid memory leaks. 1. Common memory leak problems: Memory leaks refer to the inability to release the memory space allocated by the program during operation.

Python development advice: Master and apply the principles of object-oriented programming Python development advice: Master and apply the principles of object-oriented programming Nov 22, 2023 pm 07:59 PM

Python is a powerful and flexible programming language that is widely used in software development in various fields. In the Python development process, it is very important to master and apply the principles of Object-Oriented Programming (OOP). This article will introduce some key Python development suggestions to help developers better grasp and apply the principles of object-oriented programming. First of all, the core idea of ​​object-oriented programming is to divide the problem into a series of objects and

See all articles