How can I check if a list index exists?
Question:
Seems as though
if not mylist[1]:
return False
Doesn’t work.
Answers:
In the case of integer-indexed lists, I’d simply do
if 1 < len(mylist):
...
For dicts, you can of course do
if key in mydict:
...
You just have to check if the index you want is in the range of 0
and the length of the list, like this
if 0 <= index < len(list):
it is actually internally evaluated as
if (0 <= index) and (index < len(list)):
So, that condition checks if the index is within the range [0, length of list).
Note: Python supports negative indexing. Quoting Python documentation,
If i
or j
is negative, the index is relative to the end of the string: len(s) + i
or len(s) + j
is substituted. But note that -0 is still 0.
It means that whenever you use negative indexing, the value will be added to the length of the list and the result will be used. So, list[-1]
would be giving you the element list[-1 + len(list)]
.
So, if you want to allow negative indexes, then you can simply check if the index doesn’t exceed the length of the list, like this
if index < len(list):
Another way to do this is, excepting IndexError
, like this
a = []
try:
a[0]
except IndexError:
return False
return True
When you are trying to access an element at an invalid index, an IndexError
is raised. So, this method works.
Note: The method you mentioned in the question has a problem.
if not mylist[1]:
Lets say 1
is a valid index for mylist
, and if it returns a Falsy value. Then not
will negate it so the if
condition would be evaluated to be Truthy. So, it will return False
, even though an element actually present in the list.
In the EAFP style of Python:
try:
mylist[1]
except IndexError:
print "Index doesn't exist!"
Alternative (but somewhat slower) way of doing it:
if index not in range(len(myList)):
return False
It gets a bit more verbose when accounting for negative indices:
if index not in range(-len(myList), len(myList)):
return False
assert len(mylist) >= abs(index) + int(index >= 0), "Index out of range"
or
assert len(mylist) > abs(index) - int(index < 0), "Index out of range"
Or you can do:
if index in dict(enumerate(mylist)):
return True
Although is will probably be even less efficient than range(len(mylist))
. Maybe someone should propose a keys() method for lists that returns the range of the keys in PEP.
The following approach returns the True
result for index == 0
and for negative index values (if such an index is valid for the list, for example listIn[-2]
for [0, 1, 2]
):
def isInListRange(listIn, index):
""" Description: Function to detect if list index out of range
Import: from shared.isInListRange import isInListRange
Test: python -m shared.isInListRange
"""
try:
return True if (index == 0 and len(listIn) > 0) or listIn[index] else False
except:
return False
Seems as though
if not mylist[1]:
return False
Doesn’t work.
In the case of integer-indexed lists, I’d simply do
if 1 < len(mylist):
...
For dicts, you can of course do
if key in mydict:
...
You just have to check if the index you want is in the range of 0
and the length of the list, like this
if 0 <= index < len(list):
it is actually internally evaluated as
if (0 <= index) and (index < len(list)):
So, that condition checks if the index is within the range [0, length of list).
Note: Python supports negative indexing. Quoting Python documentation,
If
i
orj
is negative, the index is relative to the end of the string:len(s) + i
orlen(s) + j
is substituted. But note that -0 is still 0.
It means that whenever you use negative indexing, the value will be added to the length of the list and the result will be used. So, list[-1]
would be giving you the element list[-1 + len(list)]
.
So, if you want to allow negative indexes, then you can simply check if the index doesn’t exceed the length of the list, like this
if index < len(list):
Another way to do this is, excepting IndexError
, like this
a = []
try:
a[0]
except IndexError:
return False
return True
When you are trying to access an element at an invalid index, an IndexError
is raised. So, this method works.
Note: The method you mentioned in the question has a problem.
if not mylist[1]:
Lets say 1
is a valid index for mylist
, and if it returns a Falsy value. Then not
will negate it so the if
condition would be evaluated to be Truthy. So, it will return False
, even though an element actually present in the list.
In the EAFP style of Python:
try:
mylist[1]
except IndexError:
print "Index doesn't exist!"
Alternative (but somewhat slower) way of doing it:
if index not in range(len(myList)):
return False
It gets a bit more verbose when accounting for negative indices:
if index not in range(-len(myList), len(myList)):
return False
assert len(mylist) >= abs(index) + int(index >= 0), "Index out of range"
or
assert len(mylist) > abs(index) - int(index < 0), "Index out of range"
Or you can do:
if index in dict(enumerate(mylist)):
return True
Although is will probably be even less efficient than range(len(mylist))
. Maybe someone should propose a keys() method for lists that returns the range of the keys in PEP.
The following approach returns the True
result for index == 0
and for negative index values (if such an index is valid for the list, for example listIn[-2]
for [0, 1, 2]
):
def isInListRange(listIn, index):
""" Description: Function to detect if list index out of range
Import: from shared.isInListRange import isInListRange
Test: python -m shared.isInListRange
"""
try:
return True if (index == 0 and len(listIn) > 0) or listIn[index] else False
except:
return False