HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Offset the elements of a Python list

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
offsetelementsthepythonlist

Problem

Have you ever wanted to move a specified amount of elements to the end of a list? This can be useful when you want to rotate the elements of a list or reorder them in a specific way.
The only thing you really need is to use slice notation to get the two slices of the list and combine them before returning. This way, you can easily move the elements to the end of the list, by rearranging the order of the slices.

Solution

def offset(lst, offset):
  return lst[offset:] + lst[:offset]

offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]

Code Snippets

def offset(lst, offset):
  return lst[offset:] + lst[:offset]

offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]

Context

From 30-seconds-of-code: offset

Revisions (0)

No revisions yet.