search
HomeBackend DevelopmentPython TutorialDetailed explanation of python lists (summary sharing)

This article brings you relevant knowledge about python, which mainly introduces issues related to lists, including accessing list elements, modifying, adding, deleting elements, organizing lists, etc. Let’s take a look at it together, I hope it will be helpful to everyone.

Detailed explanation of python lists (summary sharing)

Recommended learning: python video tutorial

A list is composed of a series of elements in a specific order ! Lists are the most commonly used Python data type and can appear as a comma-separated value within square brackets. The data items of the list do not need to be of the same type! !

1. Access list elements

The list is an ordered set, so to access any element of the list, Just tell python the position (index) of that element.
list = ['su liang','hacker','ice']print(list[0].title())  
#结果:Su Liangprint(list[1].upper())  
#结果:HACKERprint(list[2].lower())  
#结果:ice

The elements returned by python here do not contain square brackets. Adding the title method can make the first letter capitalized. upper methodmakes all uppercase,lower methodmakes all lowercase! ! These methods can make the elements we access more concise! !

1.1 The index starts from 0 instead of 1

In python, the index of the first element of the list is 0, not 1. Most Programming languages ​​are also stipulated in this way. It has been demonstrated for everyone in the above example. Python provides special syntax for accessing the last element. By specifying the index as -1, python can be accessed to the last element.

list = ['su liang','hacker','ice']print(list[-1])  #结果:iceprint(list[-2]) #结果:hacker

2. Modify, add and delete elements

Most lists created are dynamic, meaning Then you can add, delete, modify and check the list.

2.1 Modify list elements

To modify list elements, you can specify the list name and the index of the element to be modified, Then specify the new value of the element.

list = ['su liang','hacker','ice']list[1]='hacker707'print(list)#结果:['su liang', 'hacker707', 'ice']

2.2 Adding elements to the list

In many cases we need to continuously add new elements to the list. There are mainly the following methods.

2.2.1 Add (append) at the end

The simplest way to add elements to a list is to append the append() method. Use this method to add elements to end of list.

x = []def list(name):
    global x
    x.append(name)
    print(x)while True:
    name = input('输入名字:')
    list(name)

Result:
Detailed explanation of python lists (summary sharing)

2.2.2 Add (insert) at any position

Use the insert() method to add an index The sum value adds an element anywhere in the list.

list = ['su liang','hacker','ice']list.insert(1,'kiko')print(list)#结果:['su liang', 'kiko', 'hacker', 'ice']

2.3 Delete elements from the list

In many cases we need to continuously delete some elements from the list. There are mainly the following methods.

2.3.1 Use the del statement to delete

If you know where the element to be deleted is in the list, you can use the del statement.

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
print(list.pop())  #结果:ice
print(list)        #结果:['su liang', 'none', 'kiko', 'hacker']

2.3.2 Use the pop() method to delete

The pop() method deletes the element at the end of the list and allows you to continue using it.

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
print(list.pop())  #结果:ice
print(list)        #结果:['su liang', 'none', 'kiko', 'hacker']

2.3.3 Pop the element at any position in the list

In fact, you can use pop to delete any position in the list, the value needs to be indexed in brackets That’s it.

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
x = list.pop(3)
print(x)
#结果:hacker

2.3.4 Remove elements based on value (remove)

Sometimes we don’t know where the element is in the list, but only the value of the element. You can use the remove() method to delete.

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
list.remove('none')
print(list)
#结果:['su liang', 'kiko', 'hacker', 'ice']

3. Organize the list

In the list you create, the order of the elements is unpredictable. Sometimes you need to preserve the original ordering of list elements, and sometimes you need to adjust the order. Python provides many ways to organize lists, which can be used according to the situation.

3.1 使用sort()方法对列表永久排序

在使用sort方法时,默认为从小到大,总a到z进行排序,依然可以在括号内加上reverse=True进行倒序.
此时的排序是对列表永久排序,即不保留原来的列表顺序!!!

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
list.sort()
print(list)
#结果:['hacker', 'ice', 'kiko', 'none', 'su liang']
list.sort(reverse=True)
print(list)
#结果:['su liang', 'none', 'kiko', 'ice', 'hacker']

3.2 使用函数sorted()对列表临时排序

sorted相对sort来说,它保留了原列表序列。若想倒序,添加reverse参数即可。

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
list2 = sorted(list)
print(list2)
#结果:['hacker', 'ice', 'kiko', 'none', 'su liang']
print(list)
#结果:['su liang', 'none', 'kiko', 'hacker', 'ice']

3.3 倒着打印列表(reverse)

要反转列表元素的排列顺序,可使用方法reverse().注意:这并不是将列表元素按顺序打印,而是将原列表元素进行反转。reverse方法也是永久改变列表顺序的,若想恢复,再对列表再次调用该方法即可。

list = [2,5,6,4,8,7]
list.reverse()
print(list)
#结果:[7, 8, 4, 6, 5, 2]

3.4 确定列表长度(len)

使用len函数可快速获取列表的长度。

list = ['su liang', 'none', 'kiko', 'hacker', 'ice']
n = len(list)
print(n) #结果:5

推荐学习:python视频教程

The above is the detailed content of Detailed explanation of python lists (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!