my_list = [1, 2, 3, 4] last_element = my_list[-1]
4
To get the last element of a list in Python, you can use the index -1.
You can also use the pop() method to remove and return the last element of a list. This method removes the element from the list, so if you want to keep the original list intact, you can use the slicing syntax to get a copy of the last element. Here is an example:my_list = [1, 2, 3, 4] # using the pop() method to remove and return the last element last_element = my_list.pop() # using slicing to get a copy of the last element last_element = my_list[-1:]Note that the pop() method only works if the list is not empty. If the list is empty, it will raise an IndexError exception. You can check if the list is empty using the len() function and handle the exception accordingly. Here is an example:
my_list = [1, 2, 3, 4] if len(my_list) > 0: last_element = my_list.pop() else: # handle the empty list case last_element = None # or some other default value
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.