'Python, looping and get the first max value
Let's say I have this list containing these numbers: 1, 4, 8, 3, 5, 9, 2
I want to loop through this and get 8 because it's the first max value I encounter when loop through the list I'm thinking of loop through each [i], and + the if statement:
if [i] < [i+1] and [i+1] > [i+2]:
print(i)
Although this print 8 which is what I want, it also prints 9 because it satisfied the condition. Is there a way to make it stop after printing 8?!
Solution 1:[1]
Below is the code you can try though to get the first max value between i and i+1
index through the list
nums = [1, 4, 8, 3, 5, 9, 2]
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
print(nums[i])
break
Solution 2:[2]
You can use the break
statement to break out of your loop. You can check out the use of break
, continue
and pass
statements in Python here,
https://www.geeksforgeeks.org/break-continue-and-pass-in-python/
The break
statement is what is applicable to you here.
So, your code would look something like this,
for i in range(len(nums)-1):
if [i] < [i+1]:
print(i)
break
Solution 3:[3]
By "first max", I'm assuming you mean the point where the immediate next element is lower?
Thats what I understood also going by your example -
Want 8
as the output out of [1, 4, 8, 3, 5, 9, 2]
If that is what you're looking for, you can try this -
a = [1, 4, 8, 3, 5, 9, 2]
for idx, val in enumerate(a):
if val > a[idx+1]:
# print(f"{idx} : {val}")
print(val)
break
I'm checking for the 1st occurrence where an element is higher than its very next element and breaking out of the loop at that point.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alonso |
Solution 2 | |
Solution 3 | Manu Manjunath |