Find Maximum Elements From List

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, there are many ways to manipulate lists. One common task is to find the n maximum elements from a list. In this challenge, you will be asked to write a function that returns the n maximum elements from a list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/booleans -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/lists -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/tuples -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/function_definition -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/default_arguments -.-> lab-13688{{"`Find Maximum Elements From List`"}} python/build_in_functions -.-> lab-13688{{"`Find Maximum Elements From List`"}} end

N Max Elements

Write a function max_n(lst, n = 1) that takes a list lst and an optional integer n as arguments and returns a list of the n maximum elements from the provided list. If n is not provided, the function should return a list containing the maximum element of the list. If n is greater than or equal to the length of the list, the function should return the original list sorted in descending order.

Your task is to implement the max_n() function.

def max_n(lst, n = 1):
  return sorted(lst, reverse = True)[:n]
max_n([1, 2, 3]) ## [3]
max_n([1, 2, 3], 2) ## [3, 2]

Summary

In this challenge, you have learned how to find the n maximum elements from a list in Python. You have implemented a function that takes a list and an optional integer as arguments and returns a list of the n maximum elements from the provided list.

Other Python Tutorials you may like