Search

# Find Second Largest and Second Smallest from a list.

#### Example :

numbers = [3,4,2,6,8,3,5,6,1]

#### Expected output

Second Largest is : 6 Second smallest is : 2

To solve this problem we will first find the maximum and minimum from the list. we can do this by using in built min max function or by iterating the list.

```minimum = min(numbers)
maximum = max(numbers)```

or

```minimum = None
maximum = None
for i in numbers:
if minimum==None or minimum>i:
minimum = i
if maximum==None or maximum<i:
maximum = i```

Now that we know which number is smallest and greatest in the list we can find the second largest and second smallest using the same method keeping in mind that this numbers should not be equal to the numbers we found earlier.

Below is the full program in Python:

```def solution(numbers):
if len(numbers)<=2:
return None,None
first_min = min(numbers)
first_max = max(numbers)
second_min = None
second_max = None
for i in numbers:
if i>first_min:
if second_min==None or i<second_min:
second_min = i
if i<first_max:
if second_max==None or i>second_max:
second_max = i
return second_max,second_min

numbers = [3,4,2,6,8,3,5,6,1]
second_max, second_min = solution(numbers)
print("Second Largest is : ",second_max)
print("Second smallest is : ",second_min)```

See All