How do I get the last element of a list?

Viewed 2852200

How do I get the last element of a list?

25 Answers

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

You can also do:

last_elem = alist.pop()

It depends on what you want to do with your list because the pop() method will delete the last element.

To prevent IndexError: list index out of range, use this syntax:

mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

lst[-1] is the best approach, but with general iterables, consider more_itertools.last:

Code

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

list[-1] will retrieve the last element of the list without changing the list. list.pop() will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.

Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1], assuming the list is not empty.

Here is the solution for your query.

a=["first","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the last second item in the list.

Output:

>>> first
>>> last
>>> second from last

Strange that nobody posted this yet:

>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>> 

Just unpack.

Pythonic Way

So lets consider that we have a list a = [1,2,3,4], in Python List can be manipulated to give us part of it or a element of it, using the following command one can easily get the last element.

print(a[-1])

Accessing the last element from the list in Python:

1: Access the last element with negative indexing -1

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data[-1]
'w'

2. Access the last element with pop() method

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data.pop()
'w'

However, pop method will remove the last element from the list.

To avoid "IndexError: list index out of range", you can use this piece of code.

list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))

You can also use the length to get the last element:

last_elem = arr[len(arr) - 1]

If the list is empty, you'll get an IndexError exception, but you also get that with arr[-1].

If you use negative numbers, it will start giving you elements from last of the list Example

lst=[1,3,5,7,9]
print(lst[-1])

Result

9

You can use ~ operator to get the ith element from end (indexed from 0).

lst=[1,3,5,7,9]
print(lst[~0])

If you do my_list[-1] this returns the last element of the list. Negative sequence indexes represent positions from the end of the array. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

You will just need to take the and put [-1] index. For example:

list=[0,1,2]
last_index=list[-1]
print(last_index)

You will get 2 as the output.

You could use it with next and iter with [::-1]:

>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>> 
array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

Another simple solution

Couldn't find any answer mentioning this. So adding.

You could try some_list[~0] also.

That's the tilde symbol

enter image description here

METHOD 1:

L = [8, 23, 45, 12, 78]
print(L[len(L)-1])

METHOD 2:

L = [8, 23, 45, 12, 78]
print(L[-1])

METHOD 3:

L = [8, 23, 45, 12, 78]
L.reverse() 
print(L[0])

METHOD 4:

L = [8, 23, 45, 12, 78]
print(L[~0])

METHOD 5:

L = [8, 23, 45, 12, 78]
print(L.pop())

All are outputting 78

Related