0

I have a code like that,

i = 0
l1 = ['a','b','c']
while(i < len(l1)):
    if i + 2 < len(l1):
        if  l1[i + 2] == 'c':
            print("ok")
        else:
            print("None,Error!")
    else:
        print("None,Error!")
    i += 1 

As you can see, in the else part, print("None,Error!") are used in two times. In practice, they are very long but totally same so I want to merge them to make them simple.However, I need to check if i+2 is out of list bound, so I cannot rewrite it to

if i+2 < len(l1) and l1[i + 2] == 'c':

Is there any idea can solve this problem?

4daJKong
  • 1,825
  • 9
  • 21
  • Wait, what? Why are you asking how to *avoid* code reuse? – user2357112 Mar 24 '22 at 03:03
  • 1
    And you *can* rewrite it the way you say you can't. – user2357112 Mar 24 '22 at 03:04
  • 3
    Thanks to [short circuiting](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting), you can combine the `if`s with the `and` without problem – Phu Ngo Mar 24 '22 at 03:04
  • If you're thinking of writing code twice as "reusing" it, the standard term for that is code duplication. Code reuse refers to *not* writing similar code multiple times. – user2357112 Mar 24 '22 at 03:06
  • @user2357112supportsMonica thanks for your reply again, so if the problem is how to avoid to write similar code mulit times.... – 4daJKong Mar 24 '22 at 03:13

2 Answers2

1

As Phu Ngo mentions, we can take advantage of short circuiting to write

i = 0
l1 = ['a','b','c']
while(i < len(l1)):
    if i + 2 < len(l1) and l1[i + 2]=='c':
        print("ok")
    else:
        print("None,Error!")
    i+=1

If i+2<len(l1) is false, then the expression l1[i + 2]=='c' is never evaluated, which means that no error is raised.

Another solution that can be considered here is a try/except clause.

i = 0
l1 = ['a','b','c']
while(i < len(l1)):
    try:
        if l1[i+2]=='c':
            print("ok")
        else:
            raise ValueError
    except Exception:
        print("None,Error!")
    i+=1

Both result in the printouts

ok
None,Error!
None,Error!
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
0

Unless your data is large, ditch the algorithmic details and just arrange the data in a convenient way:

xs = ['a', 'b', 'c']

for x1, x2 in zip(xs, xs[2:] + [None, None]):
    print("ok" if x2 == 'c' else "None,Error!")

Yet another illustration of the general point: one rarely needs to iterate over a collection via indexes.

FMc
  • 41,963
  • 13
  • 79
  • 132