Last List Element

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 access the last element of a list. In this challenge, you will write a function that returns the last element 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`") subgraph Lab Skills python/comments -.-> lab-13681{{"`Last List Element`"}} python/lists -.-> lab-13681{{"`Last List Element`"}} python/tuples -.-> lab-13681{{"`Last List Element`"}} python/function_definition -.-> lab-13681{{"`Last List Element`"}} end

Last List Element

Write a function called last(lst) that takes a list as an argument and returns the last element of the list.

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

Summary

In this challenge, you learned how to write a function that returns the last element of a list. You can use the index -1 to access the last element of a list.

Other Python Tutorials you may like