Build-in Methods in List
Lists are ordered collections of items, and these methods allow for various operations such as adding, removing, or modifying elements, among others.
Here’s a rundown of common built-in methods for working with lists:
1.append(item)
Adds a single item to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4) # List becomes [1, 2, 3, 4]
2. extend(iterable)
Extends the list by appending all elements from the iterable (e.g., another list, tuple, etc.).
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6]) # List becomes [1, 2, 3, 4, 5, 6]
3. insert(index, item)
Inserts an item at a specified position in the list.
Example:
my_list = [1, 2, 3]
my_list.insert(1, 'a') # List becomes [1, 'a', 2, 3]
4. remove(item)
Removes the first occurrence of an item in the list. If the item is not found, it raises a ValueError
.
Example:
my_list = [1, 2, 3, 2]
my_list.remove(2) # List becomes [1, 3, 2]
5. pop([index])
Removes and returns the item at the specified index. If no index is provided, it removes and returns the last item.
Example:
my_list = [1, 2, 3]
my_list.pop() # Returns 3, list becomes [1, 2] my_list.pop(0) # Returns 1, list becomes [2]
6. clear()
Removes all items from the list, resulting in an empty list.
Example:
my_list = [1, 2, 3]
my_list.clear() # List becomes []
7. index(item, start=0, end=len(list))
Returns the index of the first occurrence of the specified item. Optionally, you can provide a start and end range to search within.
Example:
my_list = [1, 2, 3]
my_list.index(2) # Returns 1
8. count(item)
Returns the number of times the specified item appears in the list.
Example:
my_list = [1, 2, 2, 3]
my_list.count(2) # Returns 2
9. sort(key=None, reverse=False)
Sorts the list in ascending order by default. You can pass a key
function to customize sorting and use reverse=True
to sort in descending order.
Example:
my_list = [3, 1, 2]
my_list.sort() # List becomes [1, 2, 3]
my_list.sort(reverse=True) # List becomes [3, 2, 1]
10. reverse()
Reverses the elements of the list in place.
Example:
my_list = [1, 2, 3]
my_list.reverse() # List becomes [3, 2, 1]
11. copy()
Returns a shallow copy of the list.
Example:
my_list = [1, 2, 3]
new_list = my_list.copy() # new_list becomes [1, 2, 3]
12. list()
Converts an iterable (such as a string or tuple) to a list.
Example:
my_tuple = (1, 2, 3)
new_list = list(my_tuple) # new_list becomes [1, 2, 3]