+2

How can I sort a list and print the second largest element in it using python 3?

List sorting in python I'm getting a Nonetype error

4/6/2020 5:05:33 AM

Ashutosh Thite

7 Answers

New Answer

+3

you can do it in a way like this: x=[3,7,8,6] x.remove(max(x)) print(max(x)) #output is 7

+2

If your list is sorted, you don't have to iterate over all element to find the nth-max... if increasing order mx2 = list[-2] if decreasing order mx2 = list[1] ... until you've only uniques elements in the list. If values can be repeated in the list, you need to iterate only over a list subpart: def mx2(list,inc=True): i = len(list)-1 if inc else 0 inc = -1 if inc else 1 M = list[i] try: while list[i]==M: i += inc except Exception: return None return list[i]

+1

x = list(set([1, 4, 2, 4, 6])) print(x[-2]) hehe

0

>>> a = [1,2,4,5,6,72,1,3] >>> sorted(a)[-2:-1]#start 2 position from left, stop in position from end [6]#returns array >>> sorted(a)[-2:-1][0]#pick first element 6 >>>

0

v0ltr0n no needs to slice before accessing the targeted value... Francis Sullano using a set imply implicitly to iterate over the whole list (wich could be time expensive for large list and/or numerous call) ;)

0

mylist = [1, 1, 2, 2, 3, 3, 10, 10, 4, 4, 8, 8, 6, 6, 7, 7, 5, 5, 9, 9] print(sorted(set(mylist))[-2])

-1

https://www.facebook.com/profile.php?id=100047245104339