5. Dynamically allocate and reclaim memory as needed
3. List query operation
1. Get the index of the specified element in the list index()
#如果查找列表中有N个相同元素,只返回相同元素中的第一个元素的索引
lst=['hello','world',98,'hello']print(lst.index('hello'))#如果查询的元素在列表中不存在,则会抛出ValueErrorprint(lst.index('python'))#还可以在指定的start和stop之间进行查找print(lst.index('hello',1,3))#ValueError: 'hello' is not in list "world",98print(lst.index("hello",1,4))#"world",98,"hello"
2. Get a single element in the list
#正向索引从0~N-1 逆向索引从-N到-1 指定索引不存在,抛出IndexError
lst2=['hello','world',98,'hello','world',234]#获取索引为2的元素print(lst[2])print(lst2[-4])#获取索引为10的元素print(lst2[10])#IndexError: list index out of range
3. Get multiple elements in the list_slicing operation syntax format list name [start:stop:step]
5. Deletion operations of list elements (the first four are to delete elements, and the last del is to delete the list)
1. remove() deletes one element at a time. If there are duplicate elements, only the first one will be deleted. If the element does not exist, a ValueError will be thrown.
lst4=[10,20,30,40,50,20]
lst4.remove(10)#[20, 30, 40, 50]
lst4.remove(100)#ValueError: list.remove(x): x not in list
lst4.remove(20)#[10, 30, 40, 50, 20]
2. pop() deletes an element at a specified index position. If the specified index does not exist, an IndexError will be thrown. If the index is not specified, the last element in the list will be deleted.
lst4.pop(1)#[10, 40, 50, 20]
lst4.pop(10)#IndexError: pop index out of range
lst4.pop()#[10, 30, 40, 50]
3. Slicing: Deleting at least one element at a time will produce a new list object.
7. List sorting operations (two types, the sort() method changes the original list, and the sorted() method generates a new list object)
1. Using the sort() method, all elements in the list are sorted from small to large by default. You can specify reverse=True to sort in descending order.
2. Call the built-in function sorted(), you can specify reverse=True to sort in descending order, and the original list will not change (a new list object will be generated)