Home > Article > Backend Development > A Quick Guide to Python List Methods with Examples
Python lists are versatile and come with a variety of built-in methods that help in manipulating and processing data efficiently. Below is a quick reference to all the major list methods along with brief examples.
Adds an item to the end of the list.
lst = [1, 2, 3] lst.append(4) # [1, 2, 3, 4]
Removes all items from the list.
lst = [1, 2, 3] lst.clear() # []
Returns a shallow copy of the list.
lst = [1, 2, 3] new_lst = lst.copy() # [1, 2, 3]
Counts the occurrences of an item.
lst = [1, 2, 2, 3] lst.count(2) # 2
Extends the list by appending all elements from the iterable.
lst = [1, 2, 3] lst.extend([4, 5]) # [1, 2, 3, 4, 5]
Returns the index of the first occurrence of an item.
lst = [1, 2, 3] lst.index(2) # 1
Inserts an item at the specified index.
lst = [1, 2, 3] lst.insert(1, 'a') # [1, 'a', 2, 3]
Removes and returns the item at the specified index (default is the last item).
lst = [1, 2, 3] lst.pop() # 3, lst = [1, 2]
Removes the first occurrence of an item.
lst = [1, 2, 3] lst.remove(2) # [1, 3]
Reverses the items in the list in place.
lst = [1, 2, 3] lst.reverse() # [3, 2, 1]
Sorts the list in place (ascending by default).
lst = [3, 1, 2] lst.sort() # [1, 2, 3] lst.sort(reverse=True) # [3, 2, 1]
Returns a new sorted list from the items in an iterable.
lst = [3, 1, 2] sorted(lst) # [1, 2, 3]
Returns the number of items in a list.
lst = [1, 2, 3] len(lst) # 3
Returns the largest item in a list.
lst = [1, 2, 3] max(lst) # 3
Returns the smallest item in a list.
lst = [1, 2, 3] min(lst) # 1
Returns the sum of all items in a list.
lst = [1, 2, 3] sum(lst) # 6
Creates a list from an iterable.
s = "abc" lst = list(s) # ['a', 'b', 'c']
These list methods cover the core functionalities you will need while working with lists in Python. Whether it’s appending items, sorting, or making shallow copies, these methods allow you to manipulate data efficiently.
The above is the detailed content of A Quick Guide to Python List Methods with Examples. For more information, please follow other related articles on the PHP Chinese website!