To retrieve the last three elements from a Python list, you can use negative indexing or list slicing. Here are two approaches:
- Using Negative Indexing:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
last_three_elements = my_list[-3:]
print(last_three_elements)
In this approach, we use negative indexing to access elements from the end of the list. The index -1 represents the last element, -2 represents the second-to-last element, and so on. By slicing the list using [-3:]
, we retrieve the last three elements.
- Using List Slicing:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
last_three_elements = my_list[len(my_list)-3:]
print(last_three_elements)
In this approach, we use the len()
function to get the length of the list. By subtracting 3 from the length and using it as the starting index in the list slicing, we can retrieve the last three elements.
Both approaches will give you the same result: a list containing the last three elements [8, 9, 10]
. You can adjust the code to work with your specific list.
+ There are no comments
Add yours