Python Program to Get the Last Element of the List


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In Python, a list is a collection of ordered elements or items. The elements can be of any data type such as integers, floating-point numbers, strings, or even another list or dictionary. The elements in a list are separated by commas and enclosed within square brackets [ ]. The elements in a list can be accessed using their index, which starts at 0 for the first element and increments by 1 for each subsequent element. Lists are a commonly used data structure in Python and are versatile in their usage.


Python Code :

The below Python program gets the last element of a list:


# Define the list
my_list = [1, 2, 3, 4, 5]

# Get the last element of the list
last_element = my_list[-1]

# Print the last element
print("The last element of the list is:", last_element)

In this program, we define a list called my_list containing some elements. We then use the index -1 to get the last element of the list, and store it in the variable last_element. Finally, we print the last element of the list using the print() function.

Note that this program assumes that the list is not empty. If the list is empty, attempting to access my_list[-1] will result in an IndexError. To handle this case, you can add a check to ensure that the list is not empty before getting the last element. Here’s an example:


# Define the list
my_list = []

# Check if the list is not empty
if my_list:
    # Get the last element of the list
    last_element = my_list[-1]

    # Print the last element
    print("The last element of the list is:", last_element)
else:
    print("The list is empty.")

In this version of the program, we first check if the list is not empty using the if my_list: condition. If the list is not empty, we get the last element of the list and print it. If the list is empty, we print a message indicating that the list is empty.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co