Search code examples
pythonlistpeek

Checking if the next element in a python list is empty


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

Solution

  • 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'