Find N Largest Elements
Find the N largest elements in a list.
BeginnerTopic: List Programs
Python Find N Largest Elements Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to find N largest elements in a list
numbers = list(map(float, input("Enter numbers separated by space: ").split()))
N = int(input("Enter N: "))
if N <= 0:
print("N must be positive.")
else:
largest = sorted(numbers, reverse=True)[:N]
print(f"{N} largest elements:", largest)Output
Enter numbers separated by space: 1 3 5 2 4 Enter N: 3 3 largest elements: [5.0, 4.0, 3.0]
Understanding Find N Largest Elements
We sort in descending order and slice the first N elements.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.