find the last element in an array in python

To find the last element in a Python array, you can use negative indexing. In Python, the index -1 refers to the last element in an array.

Here's an example code snippet that demonstrates how to find the last element in a Python array:

main.py
my_array = [1, 2, 3, 4, 5]
last_element = my_array[-1]
print(last_element) # Output would be 5
95 chars
4 lines

In the above code snippet, we have first defined an array my_array containing five integers. Then we have used negative indexing to access the last element of this array and store it in a variable last_element. Finally, we have printed the value of last_element to the console.

Using negative indexing is a simple and efficient way to find the last element of an array in Python.

related categories

gistlibby LogSnag