Python - How does slicing work?
# What will be printed by the following snippet?
a = 'pass'
The correct answer is the string itself, but reversed. Some python types such as arrays, lists and strings support slicing, using the following syntax: [start:end:step] . For example, using as support the list a = [1, 2, 3, 4] we can see how slicing works:
- print(a[0:2]) - notice step is optional - prints 1,2
- print(a[:]) - notice start , end and step optional - prints the whole list 1, 2, 3, 4
- print(a[::2]) - goes from start through end , skipping 2 places ahead each time.
In the same fashion, the slicing done in the example will iterate over the whole list (start and end left empty), but backwards due to the -1 value of step.