To retrieve an item from a list by its index in Python, you can use square brackets
 notation or the
list.pop() method. Here are examples of both approaches:
- Using square brackets notation:
my_list = ["apple", "banana", "cherry"] # Retrieve item by index item = my_list print(item) # Output: "banana"
In this example, we have a list
my_list containing three items. To retrieve an item, we use the square brackets notation and provide the index of the item we want to access. Remember that the index starts from 0, so
my_list retrieves the first item,
my_list retrieves the second item, and so on.
my_list = ["apple", "banana", "cherry"] # Retrieve and remove item by index item = my_list.pop(1) print(item) # Output: "banana" print(my_list) # Output: ["apple", "cherry"]
In this example, we use the
pop() method to retrieve an item by its index and remove it from the list at the same time. The
pop() method takes the index as an argument and returns the item. After calling
pop(), the item is no longer present in the list.
Both approaches allow you to access an item in a list by its index. The first approach using square brackets is useful when you want to retrieve an item without modifying the list, while the second approach using
pop() is helpful when you also want to remove the item from the list.