1

I should compare the previous, actual and next values in a list. This lines of code here underneath doesn't fully works.

The results of the code are:

5 4 6
8 10 11
20 18 19

so I miss values like

9 8 10   

and values like

8 10 11

are simply wrong.

What am I missing in the enumerate method?

list=[1,2,3,4,5,4,6,7,9,8,10,11,14,15,16,20,18,19]

for i,n in enumerate (list):

    if (i + 1 < len( list ) and i - 1 >= 0):

        a = str( list[i - 1] )
        b = str( n )
        c = str( list[i + 1] )

        if a>b<c:
            print (a,b,c)
2
  • Use: a>b and b < c and why do you need to convert them from int to str? Commented Apr 20, 2021 at 14:14
  • Don't call your lists list because that makes them hide python's inbuilt list class Commented Apr 20, 2021 at 14:26

1 Answer 1

2

After the str conversion, it holds that "10" < "8" because strings are compared lexicographically. So you can simply omit those:

a = list[i - 1]
b = n 
c = list[i + 1]

You could also use zip with 1-offset slices to simplify this sort of "iterate neighbors" pattern:

lst = [1,2,3,4,5,4,6,7,9,8,10,11,14,15,16,20,18,19]  # don't shadow built-in `list`
for a, b, c in zip(lst, lst[1:], lst[2:]):
    if a > b < c:
        print(a,b,c)

5 4 6
9 8 10
20 18 19
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Schwobaseggl, interesting use of zip function, where can i find more info about this uses of zip?Regards

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.