1

I am checking consecutive indices of a list and I want to execute same piece of code in case if the consecutive elements are not equal or if the list index is out of range. Here's what I'm trying

for n in range(len(myList))
    try:
         if myList[n]==myList[n+1]:
             #some code
         else:
             #if they are not equal then do something
             #same code should execute if exception raised: index error  --> how do i do this?

Is there a way to do this elegantly without having to repeat the same code in the except block somehow?

2
  • Write a function that do what you want instead of repeating the code Commented May 9, 2014 at 8:22
  • Your code example is a bit strange. The list index will always be out of range during the last loop iteration and (unless a miracle happens) never at any other place in the code. Why would you want to handle this exception? Commented May 9, 2014 at 8:40

4 Answers 4

2

A simple way of doing this is to just modify the if statement to check that the candidate element isn't the last one, avoiding the need for a exception clause, and keeping the code short.

    for n, i in enumerate(myList):
       if n+1 != len(myList) and i == myList[n+1]:
           #some code
       else:
           #if they are not equal then do something
           #This block will also be exicuted when last element is reached
Sign up to request clarification or add additional context in comments.

Comments

1
for n in range(1, len(myList))
    if myList[n]==myList[n-1]:
         #some code
    else:
         #foo_bar()
#foo_bar()

2 Comments

I upvoted your answer. But it still showed zero just now. So someone downvoted your answer. I was just wondering why.
@HansThen haha, thanks, I agree- people should explain why they downvote an answer.
0

Check out this(As Tom Ron suggested):

def foobar():
    #the code you want to execute in both case
for n in range(len(myList)):
    try:
        if myList[n]==myList[n+1]:
            #some code
        else:
            foobar()
    except IndexError:
        foobar()

Comments

0

The other answers are good for the specific case where you can avoid raising the exception in the first place. The more general case where the exception cannot be avoided can be handled a lambda function as follows:

def test(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

if test(lambda: some_function(data), SomeException, None) is None:
    report_error('Something happened')

The key point here is that making it a lambda defers evaluation of the expression that might raise an exception until inside the try/except block of the test() function where it can be caught. test() returns either the result of the evaluation, or, if an exception in exception_list is raised, the on_exception value.

This comes from an idea in the rejected PEP 463. lambda to the Rescue presents the same idea.

(I offered the same answer in response to this question, but I'm repeating it here because this isn't exactly a duplicate question.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.