Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created September 5, 2018 18:10
Show Gist options
  • Save pknowledge/b5a9c117672078a4c1bd68cbb596dc6c to your computer and use it in GitHub Desktop.
Save pknowledge/b5a9c117672078a4c1bd68cbb596dc6c to your computer and use it in GitHub Desktop.
Python Slice
# Python Tutorial for Beginners - Python slice
# a[start:end] # items start through end-1
# a[start:] # items start through the rest of the array
# a[:end] # items from the beginning through end-1
# a[:] # a copy of the whole array
# a[start:end:step] # start through not past end, by step
# +---+---+---+---+---+---+
# | P | y | t | h | o | n |
# +---+---+---+---+---+---+
# 0 1 2 3 4 5
# -6 -5 -4 -3 -2 -1
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> b = (0,1,2,3,4,5,6,7,8,9)
>>> c = '0123456789'
>>> x = slice(0,5)
>>> a[x]
[0, 1, 2, 3, 4]
>>> a[0,5]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple
>>> a[0:5]
[0, 1, 2, 3, 4]
>>> b[4:]
(4, 5, 6, 7, 8, 9)
>>> b[:6]
(0, 1, 2, 3, 4, 5)
>>> c[:]
'0123456789'
>>> c[0:5]
'01234'
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[0:9:2]
[0, 2, 4, 6, 8]
>>> a[0:9:3]
[0, 3, 6]
>>> a[0:9:4]
[0, 4, 8]
>>> a[::4]
[0, 4, 8]
>>> c
'0123456789'
>>> c[-1]
'9'
>>> c[-2]
'8'
>>> c[-3]
'7'
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[1::-1]
[1, 0]
>>> a[:-3:-1]
[9, 8]
>>> a[-3::-1]
[7, 6, 5, 4, 3, 2, 1, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment