How to Rotate a List in Python
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]
- Described in detail in How to Use Python Slice Notation To Reverse A List Easily
>>> l = ["Mr", "Paul"]
>>> l[::-1]
['Paul', 'Mr']
MORE GENERALIST WAY: SWAPPING AND 2 POINTERS
- You are still utilizing a python’s way to swap values via tuple unpacking
>>> i,j = 0,len(l)-1
>>> while i < j:
... l[i],l[j] = l[j],l[i]
... i+=1
... j-=1
>>> l
['Paul', 'Mr']