search
HomeBackend DevelopmentPython TutorialThings to pay attention to when developing Python

Please note: This article assumes that 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]

For most beginners, Based on previous language experience, you will probably do it like this

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

But there is a better way:

bag = [elem * 2 for elem in bag]

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

2. Traverse the list

Continue with the list above.

If possible avoid doing this:

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

Instead it should be like this:

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

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 this:

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

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

But Python provides a more natural and better method!

a = 5 
b = 10 
# 交换a 和 b
a, b = b, a

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)

Let’s try another way:

bag = [0] * 10

Look, how elegant.

Note: If your list contains a list, 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]]

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]]

Also remember:

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

5. Constructing strings

You will often need to print strings. If you have a lot of 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)

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)

Much better!

6. Returning tuples

Python allows you to return multiple elements in a function, which makes life easier. But when unpacking tuples, there is a common error like this:

def binary(): 
 return 0, 1

result = binary() 
zero = result[0] 
one = result[1]

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

def binary(): 
 return 0, 1

zero, one = binary()

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

zero, _ = binary()

That’s it So efficient!

7. Access Dicts (dictionaries)

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 be tempted to do this to avoid KeyError errors:

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))

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)))

Of course you can also use setdefault instead.

This is 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)))

You can also use dict derivation.

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

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

8 Using libraries

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

Still talking about the previous example, we build a function to count the number of times a number appears in the 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]))

Some reasons for using the library:

1. The code is correct and tested.

2. Their algorithm may be optimal, so it can run faster.

3. Abstraction: They are clearly pointed and documented, and you can focus on those that have not yet been implemented.

4. In the end, it’s already 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)

This is slicing, we specify the stop point is 5, and then stop Will remove 5 elements from the list.

What to do if it is the last 5 elements?

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

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)

But you should do it this way:

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)

That’s it for the steps 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 the same 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.

Summary

The above are the tips that you should pay attention to in Python development. I hope it will be helpful to everyone in learning and using python. If you have any questions, you can leave a message to communicate.

For more related articles that you should pay attention to in Python development, please pay attention to the PHP Chinese website!


Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software