How to Get the Last Element of a List

How do I get the last element of a list?

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.

How to get the last value of an ArrayList

The following is part of the List interface (which ArrayList implements):

E e = list.get(list.size() - 1);

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

How to get last items of a list in Python?

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

the important line is a[-9:]

How to obtain the last index of a list?

len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

class MyList(list):
def last_index(self):
return len(self)-1


>>> l=MyList([1, 2, 33, 51])
>>> l.last_index()
3

Getting the last element of a list in dart

you can use last property for read/write, inherited-getter:

last is a returns the last element from the given list.

var lst = ["element1" , "element2" , "element3"];
lst.last // -> element3

or

lst[lst.length-1] //-> element3 

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

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

If you just want to access the last item in the list you can do

if (integerList.Count > 0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}

to get the total number of items in the list you can use the Count property

var itemCount = integerList.Count;

Selecting the last element of a list inside a pandas dataframe

df.column1 = df.column1.apply(lambda x: x[-1])    
print(df)

Prints:

              datetime.  column1
0 2021-04-10 00:03 00. 30.7
1 2021-04-10 00:06 00. 20.7
2 2021-04-10 00:09 00. 10.7


Related Topics



Leave a reply



Submit