If have a list, say a=[1,2,3]
, and I want to see if a[4] is null
, is there a way to do that, without using an exception or assertion?
There is 2 indexing in Python that points to the last element in the list. list[ len – 1 ] : This statement returns the last index if the list. list[-1] : Negative indexing starts from the end.
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.
To get a slice of only the first and last element of an iterable my (e.g., a list or a string), use the slicing expression my[::len(my)-1] with default start and stop operands and the step size of len(my)-1 .
Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.
len
will tell you the length of the list. To quote the docs:
len(s)
Return the length (the number of items) of an object. The argument may be a sequence
(string, tuple or list) or a mapping (dictionary).
Of course, if you want to get the final element in a list
, tuple
, or string
, since indexes are 0 based, and the length of an item is the element count, a[len(a)-1]
will be the last item.
As an aside, generally, the proper way to access the last element in an object which allows numeric indexing (str, list, tuple, etc) is using a[-1]
. Obviously, that does not involve len
though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With