Remove Last Element from Python List

PythonPythonBeginner
Practice Now

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

Introduction

In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to remove the last element of a list and get all the other elements. In this challenge, you need to create a function that returns all the elements of a list except the last one.


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`") subgraph Lab Skills python/comments -.-> lab-13659{{"`Remove Last Element from Python List`"}} python/lists -.-> lab-13659{{"`Remove Last Element from Python List`"}} python/tuples -.-> lab-13659{{"`Remove Last Element from Python List`"}} python/function_definition -.-> lab-13659{{"`Remove Last Element from Python List`"}} end

List Initial

Write a Python function called initial(lst) that takes a list as an argument and returns all the elements of the list except the last one.

def initial(lst):
  return lst[:-1]
initial([1, 2, 3]) ## [1, 2]

Summary

To solve this challenge, you need to use Python's list slicing feature. The lst[:-1] syntax returns all but the last element of the list.

Other Python Tutorials you may like