Remove List Elements

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can easily remove elements from a list using slice notation. Slice notation allows us to create a new list by taking a portion of an existing list. In this challenge, you will be asked to write a function that removes a specified number of elements from the beginning 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-13729{{"`Remove List Elements`"}} python/lists -.-> lab-13729{{"`Remove List Elements`"}} python/tuples -.-> lab-13729{{"`Remove List Elements`"}} python/function_definition -.-> lab-13729{{"`Remove List Elements`"}} python/default_arguments -.-> lab-13729{{"`Remove List Elements`"}} end

Remove List Elements

Write a function take(itr, n=1) that takes a list itr and an integer n as arguments and returns a new list with n elements removed from the beginning of the list. If n is greater than the length of the list, return the original list.

def take(itr, n = 1):
  return itr[:n]
take([1, 2, 3], 5) ## [1, 2, 3]
take([1, 2, 3], 0) ## []

Summary

In this challenge, you learned how to remove elements from the beginning of a list using slice notation in Python. You also wrote a function that takes a list and an integer as arguments and returns a new list with a specified number of elements removed from the beginning.

Other Python Tutorials you may like