To remove an element from a list by its index in Python, you can use the pop()
method of the list or use slicing to create a new list without the element at the specified index. Here are two examples:
Using the pop()
method:
The pop()
method removes and returns the element at the specified index. If you don't need the removed element, you can use pop()
without assigning the result to a variable.
python
# Create a list
my_list = [10, 20, 30, 40, 50]
# Remove the element at index 2 (30) and store it in a variable
removed_element = my_list.pop(2)
# Print the modified list and the removed element
print("Modified List:", my_list)
print("Removed Element:", removed_element)
In this example, the element at index 2 (30) is removed, and both the modified list and the removed element are printed.
Using slicing to create a new list:
You can also use slicing to create a new list that excludes the element at the specified index:
python
# Create a list
my_list = [10, 20, 30, 40, 50]
# Remove the element at index 2 (30) using slicing
my_list = my_list[:2] + my_list[3:]
# Print the modified list
print("Modified List:", my_list)
In this example, we create a new list that excludes the element at index 2 (30) using slicing. The modified list is printed without the removed element.
Both methods allow you to remove an element from a list by its index in Python. Choose the method that best suits your needs based on whether you want to keep or discard the removed element.
Comments
Post a Comment