Hướng dẫn python slicing cheat sheet

Nicholas Key

Nicholas Key

Principal Software Engineer in Test at Okta

Published Dec 16, 2016

I thought of sharing this cheat sheet that is easy enough to understand and might be useful for anyone that codes in Python or would like to know more about the various ways to slice a list in Python. My personal experience with slicing a list in Python is summarized in this image so that you may find it handy, and share it around, if you want to. However, do keep in mind that while some notations to slice a list might seem advance, they may not be as readable as compared to a few lines of codes. So, make your own judgement wisely :)

Others also viewed

Explore topics

Collection of List slicing patterns for Python

Hướng dẫn python slicing cheat sheet

Notations:

list[:]             >> All        
list[Low:]          >> Low to End      
list[:High]         >> Begining to High
list[Low:High]      >> Low to High
list[::Step]        >> Start to End with Step
list[Low::Step]     >> Low to End with Step
list[:High:Step]    >> Start to High with Step
list[Low:High:Step] >> Low to High with Step

Example

list= ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

Hướng dẫn python slicing cheat sheet

Simple

list[3]      >> 'D'
list[-3]     >> 'G'
list[:]      >> ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
list[3:]     >> ['D', 'E', 'F', 'G', 'H', 'I']
list[:3]     >> ['A', 'B', 'C']
list[-3:]    >> ['G', 'H', 'I']
list[:-3]    >> ['A', 'B', 'C', 'D', 'E', 'F']

Double

list[-12:1]  >> ['A']
list[-12:3]  >> ['A', 'B', 'C']
list[-12:-3] >> ['A', 'B', 'C', 'D', 'E', 'F']
list[1:-8]   >> []
list[1:-11]  >> []
list[1:-6]   >> ['B', 'C']
list[2:6]    >> ['C', 'D', 'E', 'F']

Double with step

list[2:7:4]  >> ['C', 'G']
list[2:7:5]  >> ['C']
list[2:7:2]  >> ['C', 'E', 'G']
list[1:8:2]  >> ['B', 'D', 'F', 'H']
list[-7:8:2] >> ['C', 'E', 'G']

More variations

list[-1::]   >> ['I']
list[-3::]   >> ['G', 'H', 'I']
list[3::]    >> ['D', 'E', 'F', 'G', 'H', 'I']
list[::-1]   >> ['I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
list[::-4]   >> ['I', 'E', 'A']
list[::4]    >> ['A', 'E', 'I']
list[::-2]   >> ['I', 'G', 'E', 'C', 'A']
list[::2]    >> ['A', 'C', 'E', 'G', 'I']

Even more variations

list[-7::2]  >> ['C', 'E', 'G', 'I']
list[-7::3]  >> ['C', 'F', 'I']
list[1::-1]  >> ['B', 'A']
list[1::-2]  >> ['B']
list[1::-7]  >> ['B']
list[6::-3]  >> ['G', 'D', 'A']


If you have any more patterns, ideas or suggestions, please share.

You can fork/start this at https://github.com/ostwalprasad/PythonListSlicingCheatsheet