-2

i have a list a=[[1,2],[3,4],[5,6]] and i need to check if all elements in sublist are in ascending order (e.g [1,2] is less than [3,4] and [5,6], and [3,4] is less than [5,6] and so on). i use the following function:

def FirstRuleLink (L):
    for i in range(0,len(L)):
        for j in range(0,len(L[i])):
            if L[i][0]<L[i+1][0] and L[i][1]<L[i+1][1]:
                return True
            else:
                return False

but the python gives me error message that index is out of range. so how could i change this code to get the correct output.

5
  • 1
    Why not just L == sorted(L)? Commented May 30, 2018 at 11:09
  • 1
    how do you think comparing [1, 2] to [3, 4] should work? Commented May 30, 2018 at 11:11
  • See point #2 in this answer. Commented May 30, 2018 at 11:12
  • sorted would not check both element of the sublist I think Commented May 30, 2018 at 11:12
  • @p.deman right, it may or may not work depending on what OP wants. Commented May 30, 2018 at 11:13

1 Answer 1

0

Here a try :

a = [[1,2],[3,4],[5,6]]

def FirstRuleLink (a):
    for i,nxt_elmnt in zip(a, a[1:]):
        if i[0] <= nxt_elmnt[0] and i[1] <= nxt_elmnt[1]:
            pass
        else:
            return False
Sign up to request clarification or add additional context in comments.

2 Comments

@YakymPirozhenko thanks for finding mistakes, please take a look and let me know how I can improve it.
I would go with all(list(t) == sorted(t) for t in zip(*a)). Both this and your solution differs from OPs intention of using strict inequalities. Also, you probably mean to return True after the for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.