50 XP

16. Second largest

Intermediate lists

Write a function second_largest(numbers) that takes a list of whole numbers and returns the second largest different number in it. Repeats count once: in [5, 5, 3] the largest is 5 and the second largest is 3.

If the list has fewer than two different numbers (it is empty, has one number, or every number is the same), return None.

Example 1

Inputnumbers = [4, 9, 2, 7]
Output7
Explanation9 is the largest and 7 comes next.

Example 2

Inputnumbers = [5, 5, 3]
Output3
ExplanationThe two 5s count as one, so 3 is next.

Example 3

Inputnumbers = [8]
OutputNone
ExplanationThere is only one different number.

Constraints

  • numbers has 0 to 100 items, in any order.
  • Each item is a whole number from -1000 to 1000. Numbers can repeat.

Submit also runs 4 more tests you can't see.

Practises Lists (lesson 9).

Code
def second_largest(numbers):
    """Find the second largest different number.

    numbers: list of int; may be empty, may repeat
    Returns: int, or None if there are fewer than two
        different numbers
    """
    # Write your code here
    pass