Python: Check if element is less than the next elements

Question:

I want to check each element in the list, if it is smaller than the next after it and print all the numbers that met the condition.

Example:

A = [3,1,2,4]
    

A[0] < A[3]

A[1] < A[2] 

A[1] < A[3]

A[2] < A[3]

And I don’t want to check the last element.

What is the best way to do that?

I tried to do that with for loop:

A = [3,1,2,4]
for i in range(0,len(A)-1):
    for j in range(i,len(A)-1):
        if A[j] < A[j + 1]:
            print(A[j],A[j + 1])
    A[j] = A[j + 1]

And the result is:

1 2
2 4
1 4

While the desired results is:

3 4
1 2
1 4
2 4
Asked By: user2733981

||

Answers:

Use a for loop and enumerate()

arr = [3, 1, 2, 4]

for i, e in enumerate(arr):
    # only if it's not the last element
    if (i + 1) != len(arr):
        if e < arr[i + 1]:
            print(f"arr[{i}] < arr[{i+1}]")

        elif e > arr[i + 1]:
            print(f"arr[{i}] > arr[{i+1}]")

        else:
            print(f"arr[{i}] = arr[{i+1}]")

Output

arr[0] > arr[1]
arr[1] < arr[2]
arr[2] < arr[3]
Answered By: puncher

You should fix some indices in comparison as well as the ranges. The first counter i should iterate from 0 to len(A)-1 and the second counter should iterate from i+1 to len(A).

The comparison should happen between A[i], A[j] instead of A[j],A[j+1]. No need for the last line A[j] = A[j + 1] because the counters get incremented automatically.

A = [3, 1, 2, 4]
for i in range(0,len(A)-1):
    for j in range(i+1,len(A)):
        if A[i] < A[j]:
            print(A[i],A[j])
3 4
1 2
1 4
2 4
Answered By: AboAmmar

Alternatively, you could try this enumeate way, just to save some slicing and some typing … 😉

If you use enumerate it will yield back a tuple with index, and number all at once, which is more elegant.

for i, a in enumerate(A):
    for j, b in enumerate(A[i+1:]):
        if a < b: print(a, b)

# Output:
3 4
1 2
1 4
2 4
Answered By: Daniel Hao
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.