Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the next element in a python list is empty

Tags:

python

list

peek

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
like image 593
BasicHorizon Avatar asked Jul 29 '26 17:07

BasicHorizon


1 Answers

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' 
like image 148
The6thSense Avatar answered Aug 01 '26 08:08

The6thSense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!