Python Slicing

names = ['john', 'paul', 'george', 'ringo']
# Defeat Laziness - With constructor, not literal!
list(enumerate(names))

[(0, 'john'), (1, 'paul'), (2, 'george'), (3, 'ringo')]

list((i - len(names), n)
    for i, n in enumerate(names))

[(-4, 'john'), (-3, 'paul'), (-2, 'george'), (-1, 'ringo')]

names[:3]

['john', 'paul', 'george']

names[3:]

['ringo']

names[-2:]

['george', 'ringo']

# Shallow Copies
names2 = names[:]
names[0] is names2[0]

True

names == names2

True

names is names2

False

# Stride
names[::-1]

['ringo', 'george', 'paul', 'john']

list(range(10))[::3]

[0, 3, 6, 9]

# Slicing a string
filename = 'resume.pdf'
filename[:4]

'resu'

filename[-3:]

'pdf'

filename[::-1]

'fdp.emuser'


References