How to Rotate a List in Python

Pavol Kutaj
1 min readSep 30, 2022

--

This is part of the educational quest to finish Leetcode’s Explore Card Introduction to Data Structure Array and String. See how my quest is going at CODE QUEST > Leet Code > Introduction to Data Structure: Array and String (AAS)

The aim of this pageđź“ť is show ways you can rotate a list in Python, illustrating a tension between Idiomatic and Generalist Approach to Programming Languages

IDIOMATIC WAY: SLICING WITH <list_name>[::-1]

>>> l = ["Mr", "Paul"]
>>> l[::-1]
['Paul', 'Mr']

MORE GENERALIST WAY: SWAPPING AND 2 POINTERS

>>> i,j = 0,len(l)-1
>>> while i < j:
... l[i],l[j] = l[j],l[i]
... i+=1
... j-=1
>>> l
['Paul', 'Mr']

LINKS

--

--

No responses yet