Extracting List Tail in Python

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 get all the elements of a list except for the first one. This can be done using the list tail method. In this challenge, you will be asked to implement a function that returns all elements in a list except for the first one.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13727{{"`Extracting List Tail in Python`"}} python/conditional_statements -.-> lab-13727{{"`Extracting List Tail in Python`"}} python/lists -.-> lab-13727{{"`Extracting List Tail in Python`"}} python/tuples -.-> lab-13727{{"`Extracting List Tail in Python`"}} python/function_definition -.-> lab-13727{{"`Extracting List Tail in Python`"}} python/build_in_functions -.-> lab-13727{{"`Extracting List Tail in Python`"}} end

List Tail

Write a function tail(lst) that takes a list as an argument and returns all elements in the list except for the first one. If the list contains only one element, return the whole list.

def tail(lst):
  return lst[1:] if len(lst) > 1 else lst
tail([1, 2, 3]) ## [2, 3]
tail([1]) ## [1]

Summary

In this challenge, you have learned how to implement a function that returns all elements in a list except for the first one. You have also learned how to handle the case where the list contains only one element. Keep practicing to improve your Python skills!

Other Python Tutorials you may like