Reverse List Function

PythonPythonBeginner
Practice Now

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

Introduction

In Python, lists and strings can be reversed using built-in functions. However, it is also possible to reverse a list or a string using slice notation.

In this challenge, you will write a function that reverses a list or a string using slice notation.


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-13709{{"`Reverse List Function`"}} python/lists -.-> lab-13709{{"`Reverse List Function`"}} python/tuples -.-> lab-13709{{"`Reverse List Function`"}} python/function_definition -.-> lab-13709{{"`Reverse List Function`"}} end

Reverse List Function

Write a Python function called reverse(itr) that takes a list or a string as its argument and returns a new list or string that contains the elements or characters in reverse order.

Your function should have the following requirements:

  • The function should be named reverse
  • The function should take a single argument, which is a list or a string
  • The function should return a new list or string that contains the elements or characters in reverse order
  • The function should not modify the original list or string
def reverse(itr):
  return itr[::-1]
reverse([1, 2, 3]) ## [3, 2, 1]
reverse('snippet') ## 'teppins'

Summary

In this challenge, you learned how to reverse a list or a string using slice notation in Python. You wrote a function called reverse that takes a list or a string as its input and returns a new list or string that contains the elements or characters in reverse order. Remember that slice notation can be used to extract a range of elements from a list or a string.

Other Python Tutorials you may like