Chapter 5: Python basic data structure - list

Sequences are the most basic data structure in Python.

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

Python has six built-in types for sequences, but the most common are lists and tuples.

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

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

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

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

1. List creation

  • what is a list

    • Sequences are the most basic data structure in Python .
  • why do you need a list

    • A variable can store one element, and a list is a "big container" that can store more than N elements, and the program can easily operate on these data as a whole
  • Lists are equivalent to arrays in other languages

  • Features of the list

    • list elements sorted in order
    • Index mapping only one data
    • Lists can store duplicate data
    • Mixed storage of any data type
    • Dynamically allocate and reclaim memory as needed
  • list diagram

    • forward index

    image-20220711222653856

    • inverted index

    image-20220711222807137

  • list creation

    To create a list, just enclose the different data items separated by commas in square brackets

    • use square brackets
    • Call the built-in function list()
  • code demo

list = ["hello", "Python", "World"]
print(id(list))
print(type(list))
print(list)

list2=list(["hello",87,"YWHh"])
print(list2)

2. List query operation

2.1 Get the index of the specified element in the list

  • Knowing that there are N identical elements in the list, only return the first element of the same element
  • ValueError is thrown if the queried element does not exist in the list
  • You can also query between the specified start and stop
lst = ["hello", "world", 98, "hello"]
# 如果列表中有相同元素,只返回列表中的第一个元素
print(lst.index("hello"))
# print(lst.index("1111"))  元素不存在
# 指定范围查找
print(lst.index("hello", 1, 4))

2.2 Get a single element in the list

  • forward index from 0 to N-1
  • Reverse index from -N to -1
  • The specified index does not exist, throws IndexError
lst = ["hello", "world", 98, "hello"]
# 正向索引:获取索引为2的元素
print(lst[2])
# 逆向索引:获取索引为-2的元素
print(lst[-2])
# 索引不存在
# print(lst[-99])

2.3 Get multiple elements in the list

  • grammatical format
列表名[start :	stop : step ]
  • slice operation
slice operation wording explain
result of slicing A copy of the original list fragment
range of slices [ start , stop ] left closed right open
The step size defaults to 1 [ start : stop ] or [ start : stop : ]
When step is a positive number, start from start and cut backwards [ : stop : step] The first element of the slice defaults to the first element of the list
[ start : : step] The last element of the slice defaults to the last element of the list
When step is a negative number, cut forward from start [ : stop : step] The first element of the slice defaults to the last element of the list
[ start : : step] The last element of the slice defaults to the first element of the list
  • code demo
# 切片操作
lst = [10, 20, 30, 40, 50, 60, 70, 80]
# 打印输出:start=1,stop=6,step=1,产生新列表
print(lst[1:6:1])
print("原列表",id(lst))
print("切列表",id(lst[1:6:1]))
# 默认步长为1
print(lst[1:6])
print(lst[1:6:])
# 正向切片
print(lst[:6:2])
print(lst[1::2])
# 逆向切片
lst = [10, 20, 30, 40, 50, 60, 70, 80]
print(lst[::-1])
print(lst[6:1:-1])
print(lst[:1:-1])
print(lst[6::-1])

2.4 Determine whether the specified element exists in the list

  • grammatical format
元素	in	列表名
元素	not in	列表名
  • code demo
lst = [10, 20, "Python", "Hello"]
print(10 in lst)
print(100 in lst)
print("Hello" in lst)
print("java" in lst)

2.5 Traversal of list elements

  • grammatical format
for 迭代变量	in	列表名	:
	操作
  • code demo
lst = [10, 20, "Python", "Hello"]
# 将列表元素依次输出
for i in lst:
    print(i)

3. Add operation of list elements

  • Add operation method
method/other Operation description
append() Adds an element to the end of the list without producing a new object
extend() Add at least one element to the end of the list
insert() Add an element anywhere in the list
slice Add at least one element anywhere in the list
  • code demo
# append():向列表的末尾添加一个元素—最常用
lst = [10, 20, 30]
print("添加元素之前:", id(lst), lst)
lst.append(100)
print("添加元素之后:", id(lst), lst)

lst2 = ["hello", "world"]
# 将lst2作为一个元素添加到列表的末尾
lst.append(lst2)
print(lst)
# 将lst2元素依次添加到列表末尾
lst.extend(lst2)
print(lst)

# 在任意位置上添加一个元素
lst.insert(1, 90)
print(lst)

lst3 = [30, 40, "hello", "python"]
# 切片:在任意位置上添加N多个元素
lst[1::]=lst3
print(lst)

Fourth, the delete operation of list elements

  • Add operation method
method/other Operation description
remove() Remove an element from the list, if there are duplicate elements, only remove the first one; if the list element does not exist, ValueError throws an exception
pop() Remove the element according to the index; if the index does not exist, an IndexError exception is thrown
slice Deleting at least one element will result in a new list object
clear() clear the list
of the delete list
  • code demo
lst = [10, 20, 30, 40, 50, 60, 30]
print("原列表:", lst)
# remove():从列表中移除一个元素,如果有重复元素,只移除第一个
lst.remove(30)
print("原列表:", lst)
# 列表元素不存在,ValueError抛出异常
# lst.remove(100)

# pop():根据索引删除元素
lst.pop(2)
print(lst)
# 如果指定的索引位置不存在,将抛出IndexError异常
# lst.pop(50)
# 不写参数,会将列表中的最后一个元素删除
lst.pop()
print(lst)

# 切片:删除至少一个元素,将会产生一个新的列表对象
new_list = lst[1:3]
print("原列表:", id(lst), lst)
print("新列表:", id(new_list), new_list)
# 不产生新的列表对象,而是删除原列表中的内容
lst[1:3] = []
print(lst)

# clear():清除列表中的所有元素
lst.clear()
print(lst)

# del语句:删除列表
del lst

Five, the modification operation of list elements

  • assigns a new value to the element at the specified index
  • assigns a new value to the specified slice
  • code demo
list = [10, 20, 30, 40]
# 一次修改一个值
list[2] = 100
print(list)  # [10, 20, 100, 40]
# 切片修改
list[1:3:] = [22, 33]
print(list)

6. Sorting operation of list elements

  • Sort operation method
method/other Operation description
sort() Call the sort() method, and all elements in the list are sorted in descending order by default . You can sort in descending order by specifying reverse=True , and operate on the original list without generating a new list object
sorted() Call the built-in function sorted()
to sort in descending order by specifying reserve=True, the original list will not change, and a new list object will be generated
  • code demo
lst = [20, 40, 10, 98, 54]
print('排序前列表', lst)  # 排序前列表 [20, 40, 10, 98, 54]
# 开始排序,调用列表对象的sort方法,默认是升序
lst.sort()
print('排序后列表', lst)  # 排序后列表 [10, 20, 40, 54, 98]
lst.sort(reverse=True)
print('新排序列表', lst)  # 新排序列表 [98, 54, 40, 20, 10]
lst.sort(reverse=False)
print('新排序列表', lst)  # 新排序列表 [10, 20, 40, 54, 98]

# 使用内置函数sorted()对列表进行排序,将产生一个新的列表对象
lst2 = sorted(lst)
print(lst2)  # [10, 20, 40, 54, 98]
lst2 = sorted(lst, reverse=True)
print(lst2)  # [98, 54, 40, 20, 10]

Seven, list generation

List generation formula, referred to as "formula for generating lists"

  • Grammatical structures
[ 表示列表元素的表达式 for 自定义变量 in 可迭代对象 ]
[ i*i for i in range(1,10) ]
  • code demo
lst = [i for i in range(1, 10)]
print(lst)
lst2 = [i * i for i in range(1, 10)]
print(lst2)

Guess you like

Origin blog.csdn.net/polaris3012/article/details/130497453