All operation methods of Python list list

1. Introduction

1 Introduction

  1. Lists are the most basic data structure in Python.

  2. Each value in the list has a corresponding position value, called an index, the first index is 0, the second index is 1, and so on.

  3. Operations that can be performed on lists include indexing, slicing, adding, multiplying, and checking membership.

  4. Additionally, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements.

  5. A list is the most commonly used Python data type, and it can appear as a comma-separated value enclosed in square brackets.

  6. The data items of the list do not need to have the same type

  7. The essence of the list list is an ordered collection

2. Create a list

Syntax: list name = [element 1, element 2, element 3...]
Explanation: the options in the list are called elements, similar to string, and the subscripts also start counting from 0.
For example:

#创建空列表
list1 = []
#格式化
list1 = list()

#创建带有元素的列表
list2 = [10, 20, 30, 10]
print(list2)
#结果
[10, 20, 30, 10]

Note: The data types of the elements in the list can be different (flexibility), and the element types in the list can be any basic data type in python or a custom data type

list3 = [33, "good", True, 10.32]
print(list3)
#结果
[33, 'good', True, 10.32]

Supplement:
An empty list can simply be represented by two square brackets ([]), with nothing inside, but if you want to create a list that takes up ten elements of space but does not include any useful content, you can use the following method, use a specific value instead to create a list:

>>> list_empty = [0]*10
>>> list_empty
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This produces a list of 10 zeros. However, sometimes it may be necessary to have a value that represents empty, meaning no elements are placed inside. At this time, you need to use None. None is a Python built-in value that exactly means "there's nothing here". Therefore, if you want to initialize a list of length 10, you can follow the example below:

>>> list_empty = [None]*10
>>> list_empty
[None, None, None, None, None, None, None, None, None, None]

In this way, each element of the list can be initialized.

3. Access to list elements

1. The value of the list

Function: access the element value in the list
Syntax: list name [index]: list1[index]
(index value range (0,len(list1)), len(list) indicates the length of the list)
Example:

list4 = [22, 33, 12, 32, 45]
#下标从0开始,最大值为len(list4)-1
print(list4[0])

Note: When the index value is greater than len(list4)-1, the following error will occur:

print(list4[5])
IndexError: list index out of range

This error is that the subscript is out of bounds [the subscript exceeds the range that can be represented]

2. Replacement of list elements

Function: Change the value of list elements
Syntax: list name[subscript] = value: list1[index] = value
Example:

list4 = [22, 33, 12, 32, 45]
list4[0] = "hello"
print(list4[0])

4. List operation

1. List combination

Syntax: List 3 = List 1 + List 2
Take out the elements in List 1 and List 2 to form a new list and return it.
Example:

list1 = [1, 2, 3]
list2 = ['hello', 'yes', 'no']
list3 = list1 + list2
print(list3)
#结果
[1, 2, 3, 'hello', 'yes', 'no']

2. List Duplication

Syntax: List 2 = List 1 * n
Example:

list1 = [1, 2, 3]
list2 = list1 * 3
print(list2)
#结果
[1, 2, 3, 1, 2, 3, 1, 2, 3]

3. Determine whether the element is in the list

Syntax: element in list
returns True if it exists, otherwise returns False
Example:

list1 = [1, 2, 3]
print(1 in list1)
#结果
True

4. List interception

Syntax: list1[start:stop:step]
Parameter 1: Indicates the start subscript value of interception, the default is 0
Parameter 2: Indicates the end subscript value of interception, defaults to the end of the list
Parameter 3: Indicates the step size of interception , the default is 1, can be specified
Note:

  1. Intercept interval [start, end), left closed and right open
  2. list1[::-1] can get a list of flashbacks
list1 = ["hello",2,True,False,3.14]
list2 = list1[:]
list3 = list1
print(list1[0:3:2])
print(list1[::-1])
print(list1[:3:-1])
print(list1[3::-1])
#结果
['hello', True]
[3.14, False, True, 2, 'hello']
[3.14]
[False, True, 2, 'hello']

Supplement:
Traverse [start, end), the interval is span, when span>0, it traverses sequentially, when span<0, it traverses backwards. If start is not input, it will default to 0, if end is not input, it will default to length.

>>> l = [i for i in range(0,15)]
>>> print(l[::2])
[0, 2, 4, 6, 8, 10, 12, 14]
  1. start: start index, starting from 0, -1 means end
  2. end: end index
  3. step: step size, end-start, when the step size is positive, values ​​are taken from left to right. When the step size is negative, the value is reversed

for example:

>>> a=[1,2,3,4]
>>> b='abcdef'
>>> print(a[1:2])
[2]
>>> print(b[2:])
cdef
>>> print(a[::-1])
[4, 3, 2, 1]
>>> print(b[::-1])
fedcba

If it is not an "veteran" who also pursues grammatical details, the function of this code may not be obvious at first glance. In fact, in order to better reflect the pythonic code, it makes full use of the reversed() function in the python library.

>>> print(list(reversed(a)))
[4, 3, 2, 1]
>>> print(list(reversed(b)))
['f', 'e', 'd', 'c', 'b', 'a']

5. [:-1] and [::-1] in Python

for example:

a='python'
b=a[::-1]
print(b) #nohtyp
c=a[::-2]
print(c) #nhy
#从后往前数的话,最后一个位置为-1
d=a[:-1]  #从位置0到位置-1之前的数
print(d)  #pytho
e=a[:-2]  #从位置0到位置-2之前的数
print(e)  #pyth

Instructions for use:

b = a[i:j]   # 表示复制a[i]到a[j-1],以生成新的list对象

a = [0,1,2,3,4,5,6,7,8,9]
b = a[1:3]   # [1,2]

# 当i缺省时,默认为0,即 a[:3]相当于 a[0:3]
# 当j缺省时,默认为len(alist), 即a[1:]相当于a[1:10]
# 当i,j都缺省时,a[:]就相当于完整复制一份a

b = a[i:j:s]    # 表示:i,j与上面的一样,但s表示步进,缺省为1.
# 所以a[i:j:1]相当于a[i:j]

# 当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1
# 所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。

6. List traversal:

# 正序遍历:
list01 = ["Googl",'Runoob',1997,2002]
for i in range(len(list01)):  #用法1    
    print(list01[i])
for item in list01:  #用法2    
    print(item)
    
# 反向遍历
for i in range(len(list01) - 1, -1, -1):    
    print(list01[i])

result:

Googl
Runoob
1997
2002
Googl
Runoob
1997
2002
2002
1997
Runoob
Googl

7. Two-dimensional list

Syntax: List = [List 1, List 2, List 3, ... , List n]
Description: The elements in the list can be Python's basic data types, or user-defined data types.
When the elements stored in the list happen to be lists again, we can call this list a two-dimensional list.
For example:

#创建二维列表,即列表中的元素还是列表
list1 = [[1, 2, 3],[2, 3, 4],[5, 4, 9]]

Two-dimensional list value (access):
Syntax: list name [subscript 1] [subscript 2]
Description: subscript 1 represents the nth list (subscript starts from 0), and subscript 2 represents the nth list The nth element
of Example:

list1 = [[1, 2, 3],[2, 3, 4],[5, 4, 9]]
print(list1[0][0])

5. List method

1. list.append(element or list)

Function: Add a new element at the end of the list [Add an element to the original list]
Note: The value in append() can be a list or an ordinary element
. For example:

>>> list1 = [3, 4, 6]
>>> list1.append(6)
>>> print(list1)
[3, 4, 6, 6]

2. list.extend(list)

Function: Add multiple values ​​in another list at one time at the end of the list
Description: The value in extend() can only be a list or tuple [an iterable object (which can be added after the for loop)], broken The elements after the iterable object are added to the list, which cannot be elements.
For example:

>>> list1 = [1,2,3]
>>> list2 = [3, 4,5]
>>> list1.extend(list2)
>>> print(list1)
[1, 2, 3, 3, 4, 5]

3. list.insert(subscript value, element or list)

Function: Insert an element at the subscript without overwriting the original data, and the original data will be extended backward.
Note: The inserted data can be an element or a list
. For example:

>>> list1 = [1,2,3]
>>> list1.insert(1,0)
>>> print(list1)
[1, 0, 2, 3]
>>> list1.insert(1,[2, 4, 8])
>>> print(list1)
[1, [2, 4, 8], 0, 2, 3]

4. list.pop(subscript value)

Function: Remove the element at the specified subscript in the list (the last element is removed by default), and return the removed data.
Description: The deleted data will be returned here
. Example:

>>> list1 = [1, [2, 4, 8], 0, 2, 3]
>>> list1.pop()
3
>>> print(list1)
[1, [2, 4, 8], 0, 2]
>>> list1.pop(2)
0
>>> print(list1)
[1, [2, 4, 8], 2]

5. list. remove(element)

Function: Remove the first matching result of an element in the list
Example:

>>> list1 = [1, 2, 3]
>>> list1.remove(2)
>>> print(list1)
[1, 3]

6. list.clear()

Function: Clear all data in the list
Example:

>>> list1 = [1, 2, 3]
>>> list1.clear()
>>> print(list1)
[]

7. list.index(x[, start[, end]])

Function: Find the first matching index value of a value (object) from the list of specified ranges.
Description: Query range [start, stop). If no range is specified, the default is the entire list.
Note: If the element is not found in the list, an error will be reported.
Example:

>>> list1 = [1, 2, 3]
>>> list1.index(2)
1
>>> list1.index(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 4 is not in list

8. list.count(element)

Function: View the number of times an element appears in the list
Example:

>>> list1 = [1, 2, 3, 1]
>>> list1.count(1)
2

9. len(list)

Function: Get the number (length) of list elements
Example:

>>> list1 = [1, 2, 3, 1]
>>> len(list1)
4

10. max(list)

Function: Get the maximum value in the list
Example:

>>> list1 = [1, 2, 3, 1]
>>> max(list1)
3

11. min(list)

Function: Get the minimum value in the list
Note: The ASCII value is compared
Example:

>>> list1 = [1, 2, 3, 1]
>>> min(list1)
1

12. list.reverse()

Function: Reverse the elements in the list, operate on the original list, and do not return a new list.
Example:

list1 = ["hello1","good1","nice","good","hello"]
print(id(list1))
list1.reverse()
print(list1)
print(list1.reverse())
print(id(list1))
#结果
2158912823880
['hello', 'good', 'nice', 'good1', 'hello1']
None
2158912823880

13. list.sort()

list.sort(reverse=False)
function: sort the elements in the list in ascending order [default reverse=False], when reverse is True, sort in descending order.
Note: Sort the original list and do not return a new list
. Example:

>>> list1 = [1, 2, 3, 1]
>>> list1.sort()
>>> print(list1)
[1, 1, 2, 3]

14. Copy by assignment

grammar:

list1 = [1, 2, 3]
list2 = list1

Features: share the same memory space, if any variable is changed, other variables will be affected.
Note: assignment copy is reference copy, similar to shortcut

list1 = [1,2,3,4,[1,2,3,4]]
list2 = list1
print(id(list1))
print(id(list2))
list2[-1] = True
print(list2)
print(list1)
#结果
1585735384392
1585735384392
[1, 2, 3, 4, True]
[1, 2, 3, 4, True]

15. Shallow copy list.copy()

grammar:

list1 = [1, 2, 3]
list2 = list1.copy()

Note: it is only applicable to one-dimensional list; shallow copy is one-dimensional memory copy, which opens up a new memory space
and incomplete memory copy, and re-opens a memory space for one-dimensional list, but if there is a two-dimensional list, because The two-dimensional list stores the address of the list in the one-dimensional list. Therefore, if a two-dimensional list appears, it is equivalent to indirectly referencing the same memory area (that is, the two-dimensional list is still a shared memory).

Example:

>>> list1 = [1, 2, 3, 1]
>>> list2 = list1.copy()
>>> print(list2)
[1, 2, 3, 1]
>>> print(id(list2))
4314525320
>>> print(id(list1))
4314524808

import copy
list1 = [1,2,3,4,[1,2,3,4]]
list3 = list1.copy()
list3[-1][-1] = True
print(id(list1))
print(id(list3))
print(list1)
print(list3)
#结果
#一维存储地址不同
1614254026312
1614254024904
#二维存储地址相同,伴随发生改变
[1, 2, 3, 4, [1, 2, 3, True]]
[1, 2, 3, 4, [1, 2, 3, True]]

16. Deep torture copy.deepcopy()

grammar:

impo copy
list2 = copy.deepcopy(list1)

Explanation: A complete memory copy is equivalent to re-copying all list elements in list1, and re-opening up a new memory space for multi-dimensional ones.
For example:

list1 = [1,2,3,4,[1,2,3,4]]
list4 = copy.deepcopy(list1)
list4[-1][-1] ="hello"
print(id(list1))
print(id(list4))
print(list1)
print(list4)
#结果
#一维存储地址不同
2215608102408
2215608101128
#二维存储地址不同,不伴随发生改变
[1, 2, 3, 4, [1, 2, 3, 4]]
[1, 2, 3, 4, [1, 2, 3, 'hello']]

17. list(tuple)

Function: convert tuple to list

>>> list1 = list((1, 2, 3, 4))
>>> print(list1)
[1, 2, 3, 4]

6. List traversal

1. Use a for loop to traverse the list

grammar:

for 变量名 in 列表 :
​	语句

Function: The for loop is mainly used to traverse the list
Traversal: refers to accessing each element in the list in turn, and obtaining the element value corresponding to each subscript
Description: Obtain each element in the list in order, assign it to the variable name, and then Execute the statement, and so on, until all the elements in the list are fetched.
For example:

>>> list1 = ['hello', 78, '你好', 'good']
>>> for item in list1:
...     print(item)
... 
hello
78
你好
good

2. Use while loop to traverse the list [use subscript loop]

grammar:

下标 = 0
while 下标 < 列表的长度:
​ 语句
​ 下标 += 1

3. Traversing subscripts and elements at the same time

grammar:

for 下标,变量 in enumerate(列表):
	语句

Example:

>>> list1 = ['hello', 78, '你好', 'good']
>>> for index,item in enumerate(list1):
...     print(index, item)
... 
0 hello
1 78
2 你好
3 good

enumerate()[枚举]函数用于一个可遍历的数据对象(如列表,元组或者字符串)组合为一个索引序列,同时列出数据与数据下标,一般使用在for循环中
enumerate(obj, [start =0])
obj:一个可迭代对象
start:下标起始位置

4. List Comprehensions

List comprehension written form:

[表达式 for 变量 in 列表]
或者
[表达式 for 变量 in 列表 if 条件]

7. Reference links

  1. Related operations and methods of Python list (list)
  2. Python3 List index() method: https://www.runoob.com/python3/python3-list.html

Guess you like

Origin blog.csdn.net/flyingluohaipeng/article/details/129324199