In Python, a list is a mutable, ordered sequence of items. Here are some of the commonly used operations that can be performed on lists:
-
Creating a list: To create a list, we can use square brackets [] or the list() constructor.
Example:
my_list = [1, 2, 3, 4, 5] my_list = list(range(1, 6))
-
Accessing list elements: We can access the elements of a list using their index.
Example:
my_list = [1, 2, 3, 4, 5] print(my_list[0]) # Output: 1 print(my_list[-1]) # Output: 5
-
Modifying list elements: We can modify the elements of a list using their index.
Example:
my_list = [1, 2, 3, 4, 5] my_list[0] = 6 print(my_list) # Output: [6, 2, 3, 4, 5]
-
Adding elements to a list: We can add elements to a list using the append() method or the + operator.
Example:
my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] my_list = [1, 2, 3] my_list = my_list + [4] print(my_list) # Output: [1, 2, 3, 4]
-
Removing elements from a list: We can remove elements from a list using the remove() method or the del keyword.
Example:
my_list = [1, 2, 3, 4, 5] my_list.remove(3) print(my_list) # Output: [1, 2, 4, 5] my_list = [1, 2, 3, 4, 5] del my_list[2] print(my_list) # Output: [1, 2, 4, 5]
-
Slicing a list: We can extract a subset of a list using slicing.
Example:
my_list = [1, 2, 3, 4, 5] print(my_list[1:3]) # Output: [2, 3]
-
Finding the length of a list: We can find the number of elements in a list using the len() function.
Example:
my_list = [1, 2, 3, 4, 5] print(len(my_list)) # Output: 5
-
Sorting a list: We can sort a list using the sort() method.
Example:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] my_list.sort() print(my_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]