Table of Contents
Reverse a list
Swap two values
Looping inside a function
减少函数调用次数
Home Backend Development Python Tutorial Four efficient tips in Python!

Four efficient tips in Python!

Apr 11, 2023 pm 07:49 PM
python programming language

Four efficient tips in Python!

Reverse a list

There are usually two ways to reverse a list in Python: slicing or​​reverse()​​ function call . Both methods can reverse a list, but be aware that the built-in function ​​reverse()​​ changes the original list, while the slicing method creates a new list.

But what about their performance? Which way is more effective? Let’s look at the following example:

Using slices:

$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]'
1000000 loops, best of 5: 15.6 usec per loop

Copy after login

Using reverse():

$ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()'
1000000 loops, best of 5: 10.7 usec per loop

Copy after login

These two Both methods can reverse a list, but be aware that the built-in function ​​reverse()​​ will change the original list, while the slicing method will create a new list.

Obviously, the built-in function ​​reverse()​​ is faster than the list slicing method!

Swap two values

Swapping two variable values ​​with one line of code is a more Pythonic approach.

Unlike other programming languages, Python does not require the use of temporary variables to exchange two numbers or values. To give a simple example:

variable_1 = 100 
variable_2 = 500
Copy after login

To exchange the values ​​of ​​variable_1​​ and ​​variable_2​​, only one line of code is needed.

variable_1, variable_2 = variable_2, variable_1
Copy after login

You can also use the same trick with dictionaries:

md[key_2], md[key_1] = md[key_1], md[key_2]
Copy after login

This trick avoids multiple iterations and complex data transformations, thus reducing execution time.

Looping inside a function

We all like to create custom functions to perform our own specific tasks. Then use ​​for​​ to loop through these functions, repeating the task multiple times.

However, using a function inside a ​​for​​ loop requires longer execution time because the function is called on each iteration.

In contrast, if a ​​for​​ loop is implemented inside a function, the function will only be called once.

To explain more clearly, let’s give an example!

First create a simple list of strings:

list_of_strings = ['apple','orange','banana','pineapple','grape']
Copy after login

Create two functions with ​​for​​ loops inside and outside the function, start simple .

def only_function(x):
    new_string = x.capitalize()
    out_putstring = x + " " + new_string
    print(output_string)

Copy after login

And a ​​for​​ function with a loop:

def for_in_function(listofstrings):
    for x in list_of_strings:
        new_string = x.capitalize()
        output_string = x + " " + new_string
        print(output_string)

Copy after login

Obviously, the output of these two functions is the same.

Then, let’s compare, which one is faster?

Four efficient tips in Python!Four efficient tips in Python!

如您所见,在函数内使用 ​​for​​ 循环会稍微快一些。

减少函数调用次数

判断对象的类型时,使用 ​​isinstance()​​ 最好,其次是对象类型标识 ​​id()​​,对象值 ​​type()​​ 最后。

# Check if num an int type
type(num) == type(0) # Three function calls
type(num) is type(0) # Two function calls
isinstance(num,(int)) # One function call

Copy after login

不要将重复操作的内容作为参数放在循环条件中,避免重复操作。

# Each loop the len(a) will be called
while i < len(a):
    statement
# Only execute len(a) once
m = len(a)
while i < m:
    statement

Copy after login

要在模块 X 中使用函数或对象 Y,请直接使用 ​​from X import Y​​ 而不是 ​​import X; then X.Y​​。这减少了使用 Y 时的一次查找(解释器不必先查找 X 模块,然后在 X 模块的字典中查找 Y)。

总而言之,你可以大量使用 Python 的内置函数。提高 Python 程序的速度,同时保持代码简洁易懂。

如果想进一步了解 Python 的内置函数,可以参考下表,或查看以下网站(https://docs.python.org/3/library/functions.html):

Four efficient tips in Python!


The above is the detailed content of Four efficient tips in 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

PHP: Is It Dying or Simply Adapting? PHP: Is It Dying or Simply Adapting? Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

The Continued Use of C  : Reasons for Its Endurance The Continued Use of C : Reasons for Its Endurance Apr 11, 2025 am 12:02 AM

C Reasons for continuous use include its high performance, wide application and evolving characteristics. 1) High-efficiency performance: C performs excellently in system programming and high-performance computing by directly manipulating memory and hardware. 2) Widely used: shine in the fields of game development, embedded systems, etc. 3) Continuous evolution: Since its release in 1983, C has continued to add new features to maintain its competitiveness.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

Golang: The Go Programming Language Explained Golang: The Go Programming Language Explained Apr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

See all articles