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
5
  • That's tuple not a list. Can you not use a for/while loop? Commented Jun 29, 2015 at 11:56
  • Have you tried the len function? Commented Jun 29, 2015 at 11:57
  • 2
    By empty do you mean "doesn't exist"? Commented Jun 29, 2015 at 11:57
  • Yes by empty I mean doesn't exist apoologies. Commented Jun 29, 2015 at 12:00
  • possible duplicate of If list index exists, do X Commented Jun 29, 2015 at 12:19

4 Answers 4

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' 
Sign up to request clarification or add additional context in comments.

1 Comment

"Easier to ask forgiveness than permission."
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.

Comments

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"

1 Comment

This is wrong for python 3 at least. See my answer.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.