How do I get the last element of a list?

Janusz

How do I get the last element of a list?

Sasha Chedygov

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I get the last element of a CMake list of unknown length?

How to get the last element of a list?

How do I count the last elements in a list after a certain element?

How do I get - the last element only - of a While Loop in python?

How do I get the last item from a list using pyspark?

purrr::pluck - how to get last element of list

How to get last element of a JSON list

How can I find the last element in a List<>?

How do I make the last column of my output include only each element of the list instead of the whole list?

How can I get a list up until the last occurrence of an element from a list?

How do I get a specific element from a std::list?

How do I get the previous element of a list using the same iterator?

How can I get the last element of an array?

In a javascript array, how do I get the last 5 elements, excluding the first element?

In bash, how do I get the index of the last element of an array without a loop

Is there a way i can do the same for everything in a list except the last element of it?

How do I get the last character of a string?

How do I get the last day of a month?

How do I get rid of the last comma?

How do I get the last character with jquery

I have a dataframe with a column that is a vector. I want to get the last element and store it in a new column. How can I do it?

Get the last element of a list in Scheme

Jenkins SCM plugin, how do I get a list of every updated file since last build?

How do I get the last inserted key in Python (>3.7) dict without iterating through the whole list?

How do I get the unique values of a list in bash preserving order and keep the last value for each unique?

How do I get size of element in a list that is in a list using stream java

How do I get a nested element in a List or a Map with a provided List in Dart?

How do I get the last row to be automatically the last populated row

How to do a different action for the last element of a list iterated through map