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?

- 9,070
- 7
- 57
- 49

- 127
- 1
- 1
- 3
-
https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator https://stackoverflow.com/questions/15226967/last-element-in-a-python-iterator https://stackoverflow.com/questions/1630320/what-is-the-pythonic-way-to-detect-the-last-element-in-a-python-for-loop https://stackoverflow.com/questions/2429098/how-to-treat-the-last-element-in-list-differently-in-python – Josh Lee Sep 28 '17 at 17:12
-
The question is not understandable. Python does not have a concept of "null"; `a[4]` isn't "null" nor is it anything else - it **does not exist** (and keep in mind that **list indices start at 0**); and "end of list was reached" does not make any sense at all because there is no **process** described here that could "reach" elements. – Karl Knechtel Mar 29 '23 at 07:41
10 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.

- 1
- 1

- 79,954
- 26
- 128
- 166
-
an even simpler way to access the last element in a list, tuple or string: a[-1] – Óscar López Oct 05 '11 at 14:33
Here is an approach which I applied in one of the Arcade Challenges from Code Fights.
Basically, the end of a list is defined by:
- list length - current index (iteration) == 1
#!/usr/bin/python3
numbers = [1, 3, 5, 8, 10, 13, 16]
list_len = len(numbers)
for n in numbers:
current_idx = numbers.index(n)
print("Current Number:", numbers[current_idx])
list_end = list_len - current_idx
if list_end != 1:
next_idx = current_idx + 1
print("Next Number: ", numbers[next_idx])
else:
print("End Of List!")

- 9,070
- 7
- 57
- 49
with a = [1,2,3]
:
a[2:3] is [3]
a[3:4] is [ ]
So a[i:i+1] != [ ] tells if is an index of a
a[i:] does the same, but a[i:] creates another list, possible very long, while a[i:i+1] is 1 element if not empty

- 26,771
- 7
- 38
- 46
Use len
if len(a) <= index:
...
Note: Your question asks how you would find out "if a[4]
is null". a[4]
isn't anything, which is why you get an IndexError
when you try to check it.

- 44,786
- 9
- 89
- 119
a[4]
in this case will throw a IndexError
exception, which isn't the same as comparing the value of a
at index 4 to None
. You can have values of None
in a list, and if you were to compare values of a
, then when you encounter a None
, it doesn't mean that the index is not found in the list. For example:
>>> a=[1,None,2]
>>> a[1]==None
True
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Since lists are contiguous and indexed sequentially, the correct way to check if an index is in a list is to compare it to the len()
of a list, but depending on the application, there are other ways around it, like catching an IndexError
, or iteration.
>>> for index, value in enumerate(a):
... print index, value
...
0 1
1 None
2 2

- 2,991
- 16
- 14
You could write a function which behaves kind of like dict.get() does for dictionaries:
def listget(list_, index, default=None):
"""Return the item for index if index is in the range of the list_,
else default. If default is not given, it defaults to None, so that
this method never raises an IndexError."""
if index >= len(list_) or index < -len(list_):
return default
else:
return list_[index]
Example usage:
>>> names = ["Mark","Frank","James"]
>>> listget(names, 2)
'James'
>>> listget(names,-3)
'Mark'
>>> listget(names,3) # returns None
>>> listget(names,4,0)
0
So it will always return a value and you get no exceptions.

- 3,557
- 3
- 25
- 29
Here is the logic statement I use to check whether the end of your list has been reached:
arr = [1,3,2,4,5]
#counter for the array
arr_counter = 0
for ele in array:
# check if end of list has been reached
if (arr_counter+1) != len(arr):
#put all your code here
pass
# increment the array counter
arr_counter += 1
Hope this helps ! :)

- 3,069
- 4
- 22
- 36
You're not providing a specific use-case, but generally for a list your would use len
to see how many elements are in the list.
if len(a) > 3:
# Do something

- 39,165
- 10
- 64
- 72
The general way to check if you're currently looking at the element at the end of a list (in any language) is to compare the current index you're looking at with the length of the list minus one (since indexes start at 0).
a[4]
isn't really anything, because it doesn't exist - some languages may implement that as being null (or undefined) but many will simply throw an exception if you try to access it instead.

- 38,173
- 8
- 62
- 76
look here: https://www.geeksforgeeks.org/python-how-to-get-the-last-element-of-list/
test_list = [1, 4, 5, 6, 3, 5]
# printing original list
print ("The original list is : " + str(test_list))
# First naive method
# using loop method to print last element
for i in range(0, len(test_list)):
if i == (len(test_list)-1):
print ("The last element of list using loop : "+ str(test_list[i]))
# Second naive method
# using reverse method to print last element
test_list.reverse() `enter code here`
print("The last element of list using reverse : "+ str(test_list[0]))

- 26
- 1
- 2