Home > database >  How do you check if an item in a list is greater than all the items before it in the list?
How do you check if an item in a list is greater than all the items before it in the list?

Time:03-30

I'm trying to check and loop through a list of numbers to see if all the numbers before than number in the list are less than that number for all the items in the list. This is what I've tried so far:

myList = [5, 8, 2, 3, 10, 7, 12]
numberList = []
for number in myList:
   if number > myList[myList.index(number) - 1]:
      numberList.append(number)

However, this only checks the number right before it in the list, not all the numbers before it. I was wondering if there was a way to fix this or a better way to approach this. The output I've been getting is [5, 8, 3, 10, 12], not [5, 8, 10, 12] like I want.


CodePudding user response:

Just track the maximum:

myList = [5, 8, 2, 3, 10, 7, 12]
numberList = []
maxx = -1
for number in myList:
   if number > maxx:
      numberList.append(number)
      maxx = number

CodePudding user response:

Use list comprehension. The walrus operator := is available in python 3.8 onwards, and is ideal for your case:

max = mylist[0]
[max := each for each in myList if each > max]
  • Related