2

So what I am trying to accomplish is to check whether an element is empty by using a counter + 1 but I keep getting index out of range which essentially means the next element doesnt exist, but instead of throwing an exception I want the program to return a boolean to my if statement is that possible..? In essence I want to peek forward to the next element of a tuple within a dictionary actually and see if it is empty.

>>> counter = 1
>>> list = 1,2,3,4
>>> print list
>>> (1, 23, 34, 46)
>>> >>> list[counter]
23
>>> list[counter + 1]
34
>>> list[counter + 2]
46

>>> if list[counter + 3]:
...     print hello
... else:
...     print bye
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
BasicHorizon
  • 191
  • 2
  • 14

4 Answers4

4

You could use try/catch to catch error if you index a not available index of a list

And the main thing it is a bad practice to name variable with keywords i.e. list,set etc

try:
    if list[counter + 3]:
        print "yes"
except IndexError:
    print 'bye' 
The6thSense
  • 8,103
  • 8
  • 31
  • 65
3

You can use len to check for whether you are within the range.

For example:

>>> l = 1,2,3,4
>>> len(l)
4

Also, a tuple is not a list. It is generally considered bad practice to name things as list or array etc.

Jay Bosamiya
  • 3,011
  • 2
  • 14
  • 33
1

The easiest way to check presence of index in tuple or list is to compare given index to length of it.

if index + 1 > len(my_list):
    print "Index is to big"
else:
    print "Index is present"
Vladyslav Lubenskyi
  • 527
  • 1
  • 7
  • 17
1

Python 3 code without exceptions:

my_list = [1, 2, 3]
print(f"Lenght of list: {len(my_list)}")
for index, item in enumerate(my_list):
    print(f"We are on element: {index}")
    next_index = index + 1
    if next_index > len(my_list) - 1:
        print(f"Next index ({next_index}) doesn't exists")
    else:
        print(f"Next index exists: {next_index}")

Prints this:

>>> Lenght of list: 3
>>> We are on element: 0
>>> Next index exists: 1
>>> We are on element: 1
>>> Next index exists: 2
>>> We are on element: 2
>>> Next index (3) doesn't exists
Saelyth
  • 1,694
  • 2
  • 25
  • 42