与python list有关的操作

尤其注意:append,+,extend的区别

Method/Function Description Example Input Resulting List/Output
append(x) Adds a single element x to the end of the list. [1, 2, 3].append(4) [1, 2, 3, 4]
extend(iter) Adds all elements of an iterable iter to the end of the list. [1, 2, 3].extend([4, 5]) [1, 2, 3, 4, 5]
insert(i, x) Inserts element x at index i. [1, 2, 3].insert(1, 10) [1, 10, 2, 3]
remove(x) Removes the first occurrence of element x. [1, 2, 3, 2].remove(2) [1, 3, 2]
pop([i]) Removes and returns the element at index i (defaults to the last element). [1, 2, 3].pop(1) 2 (list becomes [1, 3])
clear() Removes all elements from the list. [1, 2, 3].clear() []
index(x) Returns the index of the first occurrence of element x. [1, 2, 3, 2].index(2) 1
count(x) Returns the number of occurrences of element x. [1, 2, 2, 3].count(2) 2
sort() Sorts the list in ascending order (in-place). [3, 1, 2].sort() [1, 2, 3]
reverse() Reverses the elements of the list in-place. [1, 2, 3].reverse() [3, 2, 1]
copy() Returns a shallow copy of the list. [1, 2, 3].copy() [1, 2, 3] (new list)
len(list) Returns the number of elements in the list. len([1, 2, 3]) 3
sum(list) Returns the sum of all elements in the list. sum([1, 2, 3]) 6
min(list) Returns the smallest element in the list. min([1, 2, 3]) 1
max(list) Returns the largest element in the list. max([1, 2, 3]) 3
sorted(list) Returns a new sorted list (does not modify the original). sorted([3, 1, 2]) [1, 2, 3]
reversed(list) Returns a reverse iterator (use list() to convert to a list). list(reversed([1, 2, 3])) [3, 2, 1]
list(iter) Converts an iterable (e.g., tuple, string) to a list. list((1, 2, 3)) [1, 2, 3]
del list[i] Deletes the element at index i. del [1, 2, 3][1] [1, 3]
list[i:j] Slices the list from index i to j-1. [1, 2, 3, 4][1:3] [2, 3]
list + list Concatenates two lists. [1, 2] + [3, 4] [1, 2, 3, 4]
list * n Repeats the list n times. [1, 2] * 2 [1, 2, 1, 2]

posted @ 2025-01-04 16:02  yama_lei  阅读(7)  评论(0)    收藏  举报