Python’s slices are cool, just read on.

Everyone used them one way or another, i.e. `myarray` is actually slicing. Slices are 0 based, reasons:

• Easy to see slice length when only stop position is given.
• Easy to compute length - subtract stop - start.
• Easy to split sequence without overlapping - `my_list[:x], my_list[x:]`.

Slices have the following notation:

``````s[a : b : c]
``````

where a and are start/end position, and c is a step. Step also can be negative, which reverses items.

``````l = [1, 2, 3, 4, 5]
l[::]
Out: [1, 2, 3, 4, 5]
l[::-1]
Out: [5, 4, 3, 2, 1]
``````

Slices are represented as `slice` objects, i.e. `x[1:2]` is equivalent to `x.__getitem__(slice(1, 2))`. But `x` is equivalent to `x.__getitem__(slice(2, 3))`. So it does definitely make the syntax shorter, also leaving space for flexibility.

One of the practical cases of why you would want to use a `slice` object for is the following. Suppose you need to parse a table with size, name and price of pizzas, the look like the following:

``````14 Meatfest   10
12 Meatfest    8
...
``````

you know that size is the first two characters, title comes in the space of 3-14 chars, and pice is last two characters from 14 to 16. Having said that, you can express the solution in the following pythonic way:

``````line = "14 Meatfest   10"

SIZE = slice(0, 2)
TITLE = slice(3, 14)
PRICE = slice(14, 16)

line[SIZE]
line[TITLE]
line[PRICE]
``````

output:

``````line[SIZE]
Out: '14'
line[TITLE]
Out: 'Meatfest   '
line[PRICE]
Out: '10'
``````

# Assigning

You can assign to slices as well, which modifies underlying collection in place. One interesting thing about it is that source and target slice do not have to be of a matching length. For instance

``````x = list(range(10))
x[2:5] = [20, 30]
``````

results in `[0, 1, 20, 30, 5, 6, 7, 8, 9]`, because you are assigning 2 elements to a 3-element slice, and one of the elements just disappears.

# Multiplying

Multiplication simply duplicates the slice, i.e. `x * 2` becomes `[0, 1, 20, 30, 5, 6, 7, 8, 9, 0, 1, 20, 30, 5, 6, 7, 8, 9]`. For some strange reason multiplying by negative number results in an empty list. note that multiplication always creates a new object.

Thanks! You can always email me or use contact form for more questions/comments etc.

373 Words

2021-05-11