简体   繁体   中英

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

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 ie list,set etc

try:
    if list[counter + 3]:
        print "yes"
except IndexError:
    print 'bye' 

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.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM