List operation
index() function: get the index of the specified element
Syntax:
list name.index(object)
print(a.index('l'))
- When the list contains the same element, only the subscript index of the first element is displayed
- The query element does not exist, and a valueerror error is thrown
- Can be used in the specified star and stop (not including stop)
print(a.index('l',0,2))
List【】: Get the specified single element
- Forward index: citation list name [number]
- Negative index: citation list name [-number]
Slice: Get multiple specified elements. It
is a copy of the original list and a new list.
Syntax: list name [start, stop, step]
Determine whether the element exists.
Exist: element in list
does not exist: element not in list
Element traversal
for custom variable in list
Add list element
- append() adds an element after the list. Same list
- extend() adds at least one element after the list. Equivalent splicing
- insert() adds an element at the specified position in the list. Same list
- Slice = new list. Add multiple elements at the specified position in the list. Equivalent replacement
Delete list element
- remove() deletes one at a time, duplicate elements only delete the first one
- pop() deletes the element at the specified position, and deletes the last element if it is not specified
- Slice delete at least one
- clear() clear the list
- del() delete the list
Modify list elements
- Index assignment (one)
- Slice assignment (multiple)
Sort list elements
- sort() sort the original list
- sorted() generates a new list.
Default reserve=false, ascending order
reserve=true, descending order
code example
lst=[1,2,3,7,5,6,4]
print(list(lst),id(lst))
#升序
lst.sort()
print(list(lst),id(lst))
#降序
lst.sort(reverse=True)
print(list(lst),id(lst))
#id相同证明是同一个列表
Result display
list production formula
List name=[expression for element in list]
code example
lst=[i*i*i for i in range(5)]
#0-4取数,求立方,放到lst中
print(list(lst))
Result display