Python list methods
Created By: chatGPT
Python provides a variety of built-in methods to manipulate lists. Below are some common list methods and their usage.
append(): This method is used to add an item to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
# my_list now becomes [1, 2, 3, 4]
extend(): This method adds elements from another list (or any iterable) to the end of the list.
my_list = [1, 2, 3]
my_list.extend([4, 5])
# my_list now becomes [1, 2, 3, 4, 5]
insert(): This method inserts an item at a specified index in the list.
my_list = [1, 2, 3]
my_list.insert(1, 'a')
# my_list now becomes [1, 'a', 2, 3]
remove(): This method removes the first occurrence of a specified value from the list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
# my_list now becomes [1, 3, 2]
pop(): This method removes and returns an item at a given index. If no index is specified, it removes and returns the last item.
my_list = [1, 2, 3]
item = my_list.pop()
# item is 3 and my_list now becomes [1, 2]
clear(): This method removes all items from the list.
my_list = [1, 2, 3]
my_list.clear()
# my_list now becomes []
index(): This method returns the index of the first occurrence of a given item. An error is raised if the item does not exist in the list.
my_list = [1, 2, 3]
index_of_2 = my_list.index(2)
# index_of_2 is 1
count(): This method returns the number of occurrences of a specified value in the list.
my_list = [1, 2, 2, 3]
count_of_2 = my_list.count(2)
# count_of_2 is 2
sort(): This method sorts the items of the list in-place (ascending order by default).
my_list = [3, 1, 2]
my_list.sort()
# my_list now becomes [1, 2, 3]
reverse(): This method reverses the order of items in the list in-place.
my_list = [1, 2, 3]
my_list.reverse()
# my_list now becomes [3, 2, 1]
copy(): This method returns a shallow copy of the list.
Using these methods, you can effectively manipulate lists in Python to suit your needs.my_list = [1, 2, 3]
my_list_copy = my_list.copy()
# my_list_copy is [1, 2, 3]