Remove List Elements from the End

PythonPythonBeginner
Practice Now

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

Introduction

In Python, you can remove elements from a list using various methods. One such method is to remove elements from the end of the list. In this challenge, you will write a function that removes n elements from the end of 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/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") subgraph Lab Skills python/comments -.-> lab-13728{{"`Remove List Elements from the End`"}} python/lists -.-> lab-13728{{"`Remove List Elements from the End`"}} python/tuples -.-> lab-13728{{"`Remove List Elements from the End`"}} python/function_definition -.-> lab-13728{{"`Remove List Elements from the End`"}} python/default_arguments -.-> lab-13728{{"`Remove List Elements from the End`"}} end

Remove List Elements from the End

Write a function take_right(lst, n=1) that takes a list lst and an optional integer n as arguments and returns a new list with n elements removed from the end of the list. If n is not provided, the function should remove only the last element from the list.

To solve this problem, you can use slice notation to create a slice of the list with n elements taken from the end.

def take_right(itr, n = 1):
  return itr[-n:]
take_right([1, 2, 3], 2) ## [2, 3]
take_right([1, 2, 3]) ## [3]

Summary

In this challenge, you learned how to remove elements from the end of a list in Python. You also learned how to use slice notation to create a slice of a list with n elements taken from the end.

Other Python Tutorials you may like