Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Second-to-Last Element in List [duplicate]

I am able to get the second-to-last element of a list with the following:

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] >>> print(lst[len(lst)-2]) e 

Is there a better way than using print(lst[len(lst)-2]) to achieve this same result?

like image 732
PyNoob Avatar asked Oct 03 '16 19:10

PyNoob


People also ask

How do I get the second last element in a list?

As we want second to last element in list, use -2 as index.

How do I get the last and second last of a list in Python?

To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.

How do I get the last element in a list?

To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.

How do I print a specific part of a list in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.


1 Answers

There is: negative indices:

lst[-2] 
like image 191
Scott Hunter Avatar answered Sep 19 '22 02:09

Scott Hunter