2786

How do I get the last element of a list? Which way is preferred?

alist[-1]
alist[len(alist) - 1]
0

26 Answers 26

3981

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.

0
330

If your str() or list() objects might end up being empty as so: astr = '' or alist = [], then you might want to use alist[-1:] instead of alist[-1] for object "sameness".

The significance of this is:

alist = []
alist[-1]   # will generate an IndexError exception whereas 
alist[-1:]  # will return an empty list
astr = ''
astr[-1]    # will generate an IndexError exception whereas
astr[-1:]   # will return an empty str

Where the distinction being made is that returning an empty list object or empty str object is more "last element"-like then an exception object.

5
  • 48
    Downvoted because I feel the core of this answer is incorrect. Getting a list when you want an element only postpones the inevitable "list index out of range" - and that's what should happen when attempting to get an element from an empty list. For Strings astr[-1:] could be a valid approach since it returns the same type as astr[-1], but I don't think the ':' helps to deal with empty lists (and the question is about lists). If the idea is to use "alist[-1:]" as a conditional instead of "len(alist) > 0", I think it's much more readable to use the later. (happy to upvote if I missed something) Commented Jun 7, 2015 at 6:27
  • 12
    You're down vote is understandable and valid. However I find there are two basic camps on what exception objects are intended for. One certainty is that exceptions halt your app. One camp uses exceptions in try clauses as the other camp would use the if len(alist)>0: structure instead. In any event, exceptions are objects that halt your code. And as such to me are less sequence object like then returned "null"-sequences which do not halt your code. My preference is to use IF clauses to test for "null" objects instead of objects that halt my code that I preempt with a try clause.
    – DevPlayer
    Commented Jun 8, 2015 at 20:58
  • 7
    Upvoted because slice syntax is worth the discussion, however I agree with @StanKurdziel that the morphology is wrong, you're just moving the goalpost - I found my own solution was related to the primary use of 'add this to the list if you didn't already add it' (delta line graphs), so the combined expression if len(my_vector) == 0 or my_vector[-1] != update_val is a workable pattern. but it's certainly not a global solution - it would be nice to have a syntax form where None was the result Commented Mar 5, 2017 at 20:16
  • 29
    xs[-1] if xs else None
    – Gabriel
    Commented Apr 28, 2018 at 2:35
  • 5
    Why would you "avoid" an IndexError? If you try to index an empty list or string, you'll get an exception. If you want to handle that exception, use a try/except -- that's what it's there for. Commented Aug 1, 2018 at 2:18
135

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.

1
  • 9
    NOTE: it's worth knowing that this would also remove the last element from the list. Commented Oct 28, 2021 at 18:22
96

The simplest way to display last element in python is

>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

there are many other method to achieve such a goal but these are short and sweet to use.

4
  • 5
    if your list length is zero, this solution works while list[-1] will error.
    – anon01
    Commented Feb 15, 2018 at 18:42
  • 1
    @anon01 but to get the value you'd have to access the returned list and will give Index out of range. so that advantage doesnt matter. Commented Aug 14, 2022 at 7:47
  • it is a pop not a peek
    – BigChief
    Commented Nov 21, 2022 at 10:28
  • It is a peek not a pop
    – HelloWorld
    Commented Dec 14, 2022 at 18:23
89

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable - not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it's a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does... it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you're doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you're new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I'm leaving a caveat out.

Slicing

A slice of a list returns a new list - so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you're performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don't know why you'd do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it's like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can't think of a good reason to do this, unless you'll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3
2
  • 3
    This answer gets the reward for longest answer I've seen with a high solution to word rate! Commented Feb 16, 2022 at 23:33
  • One quibble: in Python the indexing is usefully considered to be between the characters in a string.
    – kd4ttc
    Commented Sep 2, 2022 at 16:52
26

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'
2
  • TIL False or 'default' == 'default'. I was expecting it to evaluate to False or bool('default') == True. Since when False or and True and yield the right-most element instead of casting everything to a boolean? It's a logical operation that doesn't yield a boolean, not very intuitive.
    – Guimoute
    Commented Dec 27, 2022 at 21:22
  • value = mylist and mylist[-1] doesn't make value None as the default when mylist is empty, it makes it mylist (an alias to the same empty list, so mutating value would mutate mylist and vice-versa). Python's boolean operators return the last thing evaluated, not a strict True/False/None result. Similarly, option 1 is dangerous, because if mylist[-1] is falsy (numerically zero, an empty collection, None, etc.) then the result will be 'default' even though mylist[-1] was available (this flaw is the main reason ontrue if condition else onfalse exists). Commented Dec 13, 2023 at 16:23
19

Here is the solution for your query.

a=["first","second","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 second item in list 
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the second last item in the list.

Output:

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

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'
11

Another method:

some_list.reverse() 
some_list[0]
2
  • This is a simple method where you can do the same operation on O(n) also, even though you've the option to do in O(1).
    – surya
    Commented Jun 8, 2021 at 4:20
  • 1
    I don't understand how this answer to "how to get the last element?" has 20 upvotes. list(reversed(reversed(reversed(reversed(some_list)))))[-1] works too but that does not make it a valid answer.
    – Guimoute
    Commented Dec 27, 2022 at 21:13
9

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.

1
  • 5
    It's probably bad to assume that mutating the original list is usually not recommended, because, after all, it is very commonly carried out
    – Aaron
    Commented Dec 1, 2016 at 11:34
8

You can also use the code below, if you do not want to get IndexError when the list is empty.

next(reversed(some_list), None)
0
8

Strange that nobody posted this yet:

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

Just unpack.

0
7

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

2
  • 3
    ***** Excellently explained. *****
    – maqs
    Commented Oct 13, 2022 at 10:25
  • great picture..
    – Konchog
    Commented Apr 1, 2023 at 19:51
6

Ok, but what about common in almost every language way items[len(items) - 1]? This is IMO the easiest way to get last element, because it does not require anything pythonic knowledge.

6
  • 5
    items[len(items) - 1] is essentially what Python is doing under the hood, but since the len of a sequence is already stored in the sequence there is no need to count it, you're creating more work than is necessary.
    – Dan Gayle
    Commented Oct 10, 2015 at 0:25
  • 29
    since you're writing Python, you really should try to be more Pythonic
    – Michael Wu
    Commented Oct 27, 2015 at 3:35
  • 6
    @MichaelWu There is no sense to do that. Pythonic way often is not self-explanatory, need more attention where you have to introduce new persons to project and, of course, wouldn't work when you have to switch to other languages like Java - you can't use Python specific knowledge. When you omit pythonic way as is possible, then also returning to project after months/years is much easier. Commented Oct 31, 2015 at 14:13
  • 8
    @Pneumokok You make point, but I would argue that list indexing is a very basic Python technique compared to say generators. Also, why bother to use anything other than C or maybe javascript if you aren't going to take advantage of individual language tools and syntax? Then you can be consistently doing everything the hard way in all of your projects. Commented Dec 3, 2015 at 15:30
  • Although it's not very pythonic I think this is in some respects better than the some_list[-1] approach because it's more logical, and shows what it is actually doing better than some_list[-1] in my opinion. Commented Nov 4, 2016 at 21:08
5

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

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

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
2

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.

1
  • 1
    While true, .pop is destructive (as clarified by other answers). It does not only get the last item from the list, but it removes it from the list as well Commented Jun 8, 2021 at 16:15
1

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.

1

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))
2
  • The problem with this solution is that in case of len(lst) == 0 it would return a string, when you are waiting for an int.
    – raulmd13
    Commented Mar 29, 2021 at 6:13
  • What I meant to say is that this method works with a given data type. It cannot be used for all types of lists. But is not a bad answer.
    – raulmd13
    Commented Mar 30, 2021 at 6:06
1

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.

1

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])
1
  • 1
    What's the difference between your answer and this answer?
    – enzo
    Commented Oct 29, 2021 at 20:24
1

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

You could try some_list[~0] also.

That's the tilde symbol

1
1

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

>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>> 
1
  • Thanks! I used this with pandas duplicated like this : duplicated = df.duplicated(subset=["Full Name"],keep=False) data_read5 = next(iter(duplicated[::-1]))
    – Mr Noob
    Commented Aug 28, 2022 at 8:33
1

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].

1
array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element

Another simple solution

0
1

The method shown in the top answer (lst[-1]) is the most Pythonic way to get the last element of a list. Yet another way is to use collections.deque from the standard library. The key is to pass the maxlen=1 parameter so that only the last element of the list remains in it.

from collections import deque
li = [1, 2, 3]
last_item = deque(li, maxlen=1)[0]         # 3

If the list can be empty and you want to avoid an IndexError, we can wrap it in iter()+next() syntax to return a default value:

li = []
next(iter(deque(li, 1)), 'default value')  # 'default value'

It also works for other iterables such as (finite) generators as well.

it = iter([1, 2, 3])
last_item = deque(it, 1)[0]                # 3

Not the answer you're looking for? Browse other questions tagged or ask your own question.