How can I get the minimum and the maximum element of a list in python

前端 未结 8 1602
执笔经年
执笔经年 2021-01-16 18:06

If a have a list like:

l = [1,2,3,4,5]

and I want to have at the end

min = 1   
max = 5

WITHOUT

相关标签:
8条回答
  • 2021-01-16 18:31

    well, as this is an assignment, I won't give you any code, you have to figure it out yourself. But basically, you loop over the list, create two variables iMin and iMax for example, and for each value compare iMin and iMax to that value and assign a new variable iBuf to that one.

    0 讨论(0)
  • 2021-01-16 18:34

    Loop through all the elements in the list with the for loop. Set the variable storing the max/min value to the fist element in the list to start with. Otherwise, you could end up with invalid values.

    max_v=l[0]
    for i in l:
        if i>max_v:
            max_v=i
    
    min_v=l[0]
    for i in l:
        if l<min_v:
            min_v=i
    
    0 讨论(0)
提交回复
热议问题