Remove Last Element from Python List | Challenge

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-13127{{"`Remove Last Element from Python List | Challenge`"}} python/lists -.-> lab-13127{{"`Remove Last Element from Python List | Challenge`"}} python/tuples -.-> lab-13127{{"`Remove Last Element from Python List | Challenge`"}} python/function_definition -.-> lab-13127{{"`Remove Last Element from Python List | Challenge`"}} end

List Initial

Problem

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.

Example

initial([1, 2, 3]) ## [1, 2]
initial(['apple', 'banana', 'orange', 'grape']) ## ['apple', 'banana', 'orange']

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