Drop List Elements from the Left

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use slice notation to remove elements from a list. In this challenge, you will need to write a function that removes a specified number of elements from the left 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-13625{{"`Drop List Elements from the Left`"}} python/lists -.-> lab-13625{{"`Drop List Elements from the Left`"}} python/tuples -.-> lab-13625{{"`Drop List Elements from the Left`"}} python/function_definition -.-> lab-13625{{"`Drop List Elements from the Left`"}} python/default_arguments -.-> lab-13625{{"`Drop List Elements from the Left`"}} end

Drop List Elements from the Left

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

def drop(a, n = 1):
  return a[n:]
drop([1, 2, 3]) ## [2, 3]
drop([1, 2, 3], 2) ## [3]
drop([1, 2, 3], 42) ## []

Summary

In this challenge, you learned how to use slice notation to remove elements from a list in Python. You also wrote a function that removes a specified number of elements from the left of a list.

Other Python Tutorials you may like