OKPEDIA PYTHON LISTA EN

How to get the last element of a list in Python

To find the last element of a list, type the list name with index -1 in square brackets.

namelist[-1]

The last element of the list is always identified by the negative index -1.

The number of elements in the list is irrelevant.

Example

Example 1

Create a list with four elements

>>> color=['blue', 'red', 'green', 'yellow']

Take the last element of the list by relative index -1.

>>> color[-1]

The output result is the following:

'yellow'

It reads the item at the bottom of the list.

Example 1

To read the penultimate element of the list, use the relative index -2.

>>> colori[-2]
'verde'

Esempio 3

To read the last two elements of the list, type the index [-2:] by slicing technique.

>>> colori[-2:]
['verde', 'giallo']

The result is a sub-list with the last two items of the main list.

https://how.okpedia.org/en/python/how-to-get-the-last-element-of-a-list-in-python


Report us an error or send a suggestion to improve this page


Python List


FacebookTwitterLinkedinLinkedin