1

I'd like to check whether the current element in my list is larger than all the other previous elements in the list, within a for loop in Python:

list_height = [187, 241, 319, 213, 541, 259, 319, 381] # an example, input depends on the user
length = len(list_height)
list_floor2 = [] # empty list for storage purposes

# For loop
for i in range(length):
    floor1 = list_height[i]
    if i == 0:
        list_floor2.append(floor2)
    elif list_height[i] > list_height[0] and list_height[i] > list_height[i - 1]:
        floor1 = list_hoogte[i - 1]
        list_floor2.append(floor2)   

Instead of list_height[i] > list_height[i - 1] in the elif statement I'd like to not only check whether the current index (i) > the previous element in list_height (so not only index i - 1), BUT whether current index (i) > all previous elements in list_height.

How can I select all previous elements in the list? I've tried all() and list_height[:i] but I always get the same error:

TypeError: '>' not supported between instances of 'int' and 'list'

4
  • Your code doesn't run (NameError: name 'floor2' is not defined. Did you mean: 'floor1'?)! Also, can you provide your expected output, so people can ensure their code works to your expectations, please? Commented Oct 10, 2022 at 8:54
  • 1
    think of it this way - assume you've reached the i-th element somehow and you know for sure that a[i] is larger than a[i-1], a[i-2] etc. Now, when you check a[i+1], do you really need to check all of the previous elements a[i], a[i-1], a[i-2]? Or just one of them? If yes, which one? Commented Oct 10, 2022 at 8:55
  • @gog - that only works if comparison between the list elements is always transitive... which is fine for integers, but may not be true in the general case; consider rock-paper-scissors... Commented Oct 10, 2022 at 9:25
  • what if two consecutive elements are equal ? Show the expected output as well ? Commented Oct 10, 2022 at 9:27

4 Answers 4

2

You can do this with enumerate and max,

[v for i, v in enumerate(list_height) if v >= max(list_height[:i+1])]

# Output
[187, 241, 319, 541]
Sign up to request clarification or add additional context in comments.

2 Comments

I like list comprehensions. Very tidy answer.
This combines the limitations of both of the other answers; it's O(n²) and it depends on transitive comparison
2

As already in the comments mentioned, you don't actually need to check every single element till the current index. Check in each iteration for the maximum value, if the current number is bigger, you have a current maximum currrent_max, else you continue. If there is a new maximum (which automatically is also bigger than every number before), you assign that number as current_max and append the current value in the second list.

list_height = [187, 241, 319, 213, 541, 259, 319, 381]
list_floor2 = []

for i, num in enumerate(list_height):
    if i==0:
        list_floor2.append(num)
        current_max = num
    else:
        if num >= current_max:
            current_max = num
            list_floor2.append(num)

print(list_floor2)
[187, 241, 319, 541]

4 Comments

This only works if the list contains numbers or other items that have a transitive >=; it won't work if the items are dice or election candidates or similar
yes, but that is what the OP provided as example and therefore it works.
It's commented as "input depends on user", so it's reasonable to point out limitations?
ok, yes, that's true. Considered that it is a valid point, but I more understood it that the input list (of numbers) is given by a User Input.
1

Here is my solution:

The for-loop will iterate through the list_height list. And using the all function, will check to see if the current value (value[1]) is greater than any previous number in the list. If True, it will print the line with a True value at the end, otherwise it will print a False value at the end.

list_height = [187, 241, 319, 213, 541, 259, 319, 381]

for value in enumerate(list_height):
    if all(x < value[1] for x in list_height[0:value[0]]):
        print(f"{value[0]}-{value[1]} : True")
    else:
        print(f"{value[0]}-{value[1]} : False")

OUTPUT:

0-187 : True
1-241 : True
2-319 : True
3-213 : False
4-541 : True
5-259 : False
6-319 : False
7-381 : False

Or if you want more succinct code:

list_height = [187, 241, 319, 213, 541, 259, 319, 381]

for i,num in enumerate(list_height):
    val = all(x < num for x in list_height[0:i])
    print(f"{i}-{num} : {val}")

This provides the same output.

2 Comments

In worst case, all will take O(n) so overall, this will take 0(n^2) ?
Yeah, this is O(n²); if the list items are guaranteed to have transitive comparison, it'll be more efficient to use Rabinzel's answer
0
length = len(list_height)
list_floor2 = [] # empty list for storage purposes

# check whether the current element in my list is larger than all the other previous elements in the list
def Check(i):
    is_larger=True
    for j in range(i):
        if(list_height[j] > list_height[i]):
            is_larger=False
            break
    return is_larger 
# For loop
for i in range(length):
    floor1 = list_height[i]
    if Check(i):
        list_floor2.append(floor1)

1 Comment

Welcome to Stack Overflow! Please refrain from code-only answers. Explain what your code does and how it solves the OP's problem. Thanks!