[Learn python] get last element in list
There are few ways to get the last element in the list:
- You can use
pop()
function that returns the last element but also deletes it from the list. - Use index
[-1]
my_list = ['apple', 'pineapple', 'orange', 'grape']
last_element = my_list.pop()
print(f"The last element in list is '{last_element}'")
print(f"List after pop: {my_list}")
Output:
The last element in list is 'grape'
List after pop: ['apple', 'pineapple', 'orange']
Use -1
index to get the last element of the list:
my_list = [5, 8, 14, 11]
last_element = my_list[-1]
print(f"The last element in list is '{last_element}'")
print(f"List: {my_list}")
Output:
The last element in list is 11
List: [5, 8, 14, 11]