Rotate List Elements

PythonPythonBeginner
Practice Now

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

Introduction

In this challenge, you will be tasked with creating a function that rotates a list by a specified amount of elements.


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-13711{{"`Rotate List Elements`"}} python/lists -.-> lab-13711{{"`Rotate List Elements`"}} python/tuples -.-> lab-13711{{"`Rotate List Elements`"}} python/function_definition -.-> lab-13711{{"`Rotate List Elements`"}} end

Rotate List Elements

Write a function roll(lst, offset) that takes in a list lst and an integer offset. The function should move the specified amount of elements to the start of the list. If offset is positive, the elements should be moved from the end of the list to the start. If offset is negative, the elements should be moved from the start of the list to the end.

Return the modified list.

def roll(lst, offset):
  return lst[-offset:] + lst[:-offset]
roll([1, 2, 3, 4, 5], 2) ## [4, 5, 1, 2, 3]
roll([1, 2, 3, 4, 5], -2) ## [3, 4, 5, 1, 2]

Summary

In this challenge, you learned how to rotate a list by a specified amount of elements. You used slice notation to get the two slices of the list and combine them before returning.

Other Python Tutorials you may like