Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if end of list was reached?

Tags:

python

list

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?

like image 751
dumpstercake Avatar asked Oct 05 '11 13:10

dumpstercake


People also ask

How do you check if we have reached the end of the list in Python?

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.

How do you find the end 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 you find the last element of a slicing list?

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 .

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

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.


1 Answers

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.

like image 63
cwallenpoole Avatar answered Oct 01 '22 20:10

cwallenpoole