search
HomeBackend DevelopmentPython TutorialWhat are the basic operations on python lists?

The basic operations of python lists are: 1. Create a list, just enclose different data items separated by commas in square brackets; 2. Add new elements; 3. Traverse the list; 4. Access the list The value; 5. Delete elements from the list.

What are the basic operations on python lists?

Related free learning recommendations: python tutorial( Video)

The basic operations of python lists are:

Mainly introduces the detailed operation methods of lists (List) in Python, including creating, For access, update, delete, other operations, etc., friends in need can refer to it.

1. Create a list. Just enclose the different data items separated by commas in square brackets

 List = ['wade','james','bosh','haslem']

Like the index of the string, the list index starts from 0. The list can be intercepted, combined, etc.

2. Add new elements

 1 List.append('allen') #方式一:向list结尾添加 参数object
 2 >>> a=[1,2,3,4]
 3 >>> a.append(5)
 4 >>> print(a)
 5 [1, 2, 3, 4, 5]
 6 
 7 List.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object
 8 >>> a=[1,2,4]
 9 >>> a.insert(2,3)
10 >>> print(a)
11 [1, 2, 3, 4]
12 
13 List.extend(tableList)  #方式三:扩展列表,参数:iterable参数
14 >>> a=[1,2,3]
15 >>> b=[4,5,6]
16 >>> a.extend(b)
17 >>> print(a)
18 [1, 2, 3, 4, 5, 6]

3. Traverse the list

for i in List:
   print i,

4. Access the values ​​in the list

Use subscript index to access the values ​​in the list. You can also use square brackets to intercept characters, as shown below:

>>> List = [1, 2, 3, 4, 5, 6, 7 ]
 >>> print(List[3])
 4

5. Delete elements from list

 1 List.remove()   #删除方式一:参数object 如有重复元素,只会删除最靠前的
 2 >>> a=[1,2,3]
 3 >>> a.remove(2)
 4 >>> print(a)
 5 [1, 3]
 6 
 7 List.pop()   #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素
 8 >>> a=[1, 2, 3, 4, 5, 6]
 9 >>> a.pop()
10 6
11 >>> print(a)
12 [1, 2, 3, 4, 5]
13 
14 
15 del List #删除方式三:可以删除整个列表或指定元素或者列表切片,list删除后无法访问。
16 >>> a=[1, 2, 3, 4, 5, 6]
17 >>> del a[5]
18 >>> print(a)
19 [1, 2, 3, 4, 5]
20 >>> del a
21 >>> print(a)
22 Traceback (most recent call last):
23   File "<pyshell#93>", line 1, in <module>
24     print(a)

6. Sort and reverse code

 1 List.reverse()
 2 >>> a=[1, 2, 3, 4, 5, 6]
 3 >>> a.reverse()
 4 >>> print(a)
 5 [6, 5, 4, 3, 2, 1]
 6 
 7 
 8 List.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数
 9 >>> a=[2,4,6,7,3,1,5]
10 >>> a.sort()
11 >>> print(a)
12 [1, 2, 3, 4, 5, 6, 7]
13 #python3X中,不能将数字和字符一起排序,会出现此报错
14 >>> a=[2,4,6,7,3,1,5,&#39;a&#39;]
15 >>> a.sort()
16 Traceback (most recent call last):
17   File "<pyshell#104>", line 1, in <module>
18     a.sort()
19 TypeError: unorderable types: str() < int()

7. Python list interception

Python’s list interception has the same type as string operation, as shown below:

L = [&#39;spam&#39;, &#39;Spam&#39;, &#39;SPAM!&#39;]
 操作:
 Python 表达式 结果 描述 
L[2] &#39;SPAM!&#39; 读取列表中第三个元素 
 L[-2] &#39;Spam&#39; 读取列表中倒数第二个元素 
 L[1:] [&#39;Spam&#39;, &#39;SPAM!&#39;] 从第二个元素开始截取列表

8. Python list operation functions and methods

List operations include the following functions:

1. cmp(list1, list2): compare elements of two lists (python3 has been discarded)

2. len(list): list Number of elements

3. max(list): Returns the maximum value of list elements

4. min(list): Returns the minimum value of list elements

5. list(seq ): Convert tuple to list

 1 列表操作常用操作包含以下方法:
 2 1、list.append(obj):在列表末尾添加新的对象
 3 2、list.count(obj):统计某个元素在列表中出现的次数
 4 3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
 5 4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
 6 5、list.insert(index, obj):将对象插入列表
 7 6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
 8 7、list.remove(obj):移除列表中某个值的第一个匹配项
 9 8、list.reverse():反向列表中元素
10 9、list.sort([func]):对原列表进行排序

The above is the detailed content of What are the basic operations on python lists?. For more information, please follow other related articles on 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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.