In this tutorial, we will learn how to print the second maximum value in a list using Python.
The second maximum value is the second largest number in the list, coming after the largest one.
We will use different approaches to find the second maximum value, and you can choose the one that fits your needs the best.
Approach 1: Using the sort() method
Step 1: Create a list
First, let’s create a list of random numbers that we’ll use to find the second maximum value.
1 |
numbers = [12, 5, 9, 18, 62, 32, 45] |
Step 2: Sort the list in descending order
We will use the sort() method to sort the list and then print the second maximum value by accessing the second element in the sorted list.
1 2 |
# Sort the list in descending order numbers.sort(reverse=True) |
Step 3: Print the second maximum value
After sorting the list in descending order, you can print the second maximum value by accessing the second element in the list.
1 2 |
# Print the second maximum value print("Second maximum value:", numbers[1]) |
Approach 2: Using the max() function and list comprehensions
Step 1: Create a list
Let’s create a list of random numbers that we’ll use to find the second maximum value.
1 |
numbers = [12, 5, 9, 18, 62, 32, 45] |
Step 2: Find the maximum value and create a new list without the maximum value
We will use the max() function to find the maximum value in the list and then create a new list using list comprehension, removing the maximum value from it.
1 2 3 4 5 |
# Find the maximum value max_value = max(numbers) # Create a new list without the maximum value new_list = [x for x in numbers if x != max_value] |
Step 3: Find the second maximum value
Now, we can find the second maximum value by using the max() function again on the new list.
1 2 3 4 5 |
# Find the second maximum value second_max_value = max(new_list) # Print the second maximum value print("Second maximum value:", second_max_value) |
Full Code
Here is the full code for both approaches:
1 2 3 4 5 6 7 8 9 10 11 |
### Approach 1 ### numbers = [12, 5, 9, 18, 62, 32, 45] numbers.sort(reverse=True) print("Second maximum value (Approach 1):", numbers[1]) ### Approach 2 ### numbers = [12, 5, 9, 18, 62, 32, 45] max_value = max(numbers) new_list = [x for x in numbers if x != max_value] second_max_value = max(new_list) print("Second maximum value (Approach 2):", second_max_value) |
The output for the above code will be:
Second maximum value (Approach 1): 45 Second maximum value (Approach 2): 45
Conclusion
In this tutorial, we learned how to print the second maximum value in a list using Python.
We looked at two different approaches to achieve this: using the sort() method and using the max() function with list comprehensions.
Choose the approach that suits your requirements best, and feel free to modify the code as needed. Happy coding!