Slices in Python

Introduction

To your attention the slicing guide (AKA sushi operator, slice, slice)! Probably everyone who writes in Python knows about the syntax for cutting out parts of a sequence – s[a:b]… For now, we’ll look at both the most obvious and lesser known facts about the slice operation.

(But before we start, we need to clarify that in Python, as in many other languages, the last element is not included in slices and ranges, which corresponds to indexing from scratch. seq[начало:конец:шаг] (To evaluate the given expression, Python calls seq.__getitem__) – takes a slice from the BEGINNING to the END (not including it), with a step of STEP. By default, START = 0, END = object length, STEP = 1. Accordingly, some, and possibly all (seq[:], поговорим об этом позже) parameters can be omitted).

Obtaining a slice

“Python”

P

Y

T

H

O

N

0

1

2

3

4

5

-6

-5

-4

-3

-2

-1

>>> some_str = "Python"
>>> some_str[:1]  # Задаём конечным индексом 1, а т.к. конец не включается, мы получим первый элемент последовательности ('P').
'P'
>>> PYTH = slice(0, 4)  # Вместо того чтоб загромождать код вшитыми диапазонами, мы можем проименовать их (например для упрощения разбора накладной). 
>>> some_str[PYTH]
'Pyth'
>>> some_str[::2]  # Шагаем через букву.
'Pto'

A little about NumPy

Operator [] can take multiple indices or slices, separated by commas a[m:n, k:l]… This is mainly used in NumPy to get a 2D slice and a[i, j] to get one element of a two-dimensional array. Accordingly, to calculate a[i, j] Python calls a.__getitem__((i, j))… By the way, since “..." (the only instance of the ellipsis class) is recognized as a token, then we can use it in slices as well. The use of this was found in the same NumPy for the reduced creation of a slice of a two-dimensional array. More details – https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial

Removal by slice

We can also delete elements of a sequence by slice, taking into account the fact that it supports deleting elements (mutable))). I will give an example with a runtime class SupportsDeletion

>>> import typing

>>> @typing.runtime_checkable
>>> class SupportsDeletion(typing.Protocol):
>>>     def __delitem__(self, key: typing.Any) -> typing.Any:
>>>         ...

>>> for builtin_type in (list, dict, str, tuple):
>>>     print(builtin_type.__name__, "->", isinstance(builtin_type, SupportsDeletion))

list -> True
dict -> True
str -> False
tuple -> False
>>> seq = [1, 2, 3, 4]
>>> del seq[:3]  # Удаляем первых три элемента последовательности.
>>> seq
[4]

Life hacks 🙂

# 1 You can flip the sequence if you ask for a slice seq[::-1]

>>> seq = (1, 2, 3, 4, 5, 6)
>>> seq[::-1]
(6, 5, 4, 3, 2, 1)

# 2 How can I remove all list items using a slice without destroying the list object itself? (Of course, the same result can be obtained by calling the method .clear() the list, but we are talking about slices now + it is not in the second version of python).

>>> seq = [1, 2, 3, 4, 5, 6]
>>> id(seq)
2071031395200
>>> del seq[:]
>>> id(seq)
2071031395200
>>> seq
[]

No. 3 In addition to clearing lists, slicing can also be used to replace all items in a list without creating a new list object. This is a great shorthand for clearing a list and then manually filling it up again:

>>> seq = [1, 2, 3, 4, 5, 6, 7]
>>> original_list = seq
>>> seq[:] = [1, 2, 3]
>>> seq
[1, 2, 3]
>>> original_list
[1, 2, 3]
>>> original_list is seq
True

The above code example replaced all elements in seqbut did not destroy and recreate the list as such. For this reason, the old references to the original list object are still valid.

No. 4 Making small copies of existing lists:

>>> seq = [1, 2, 3, 4, 5, 6, 7]
>>> copied_list = seq[:]
>>> copied_list
[1, 2, 3, 4, 5, 6, 7]
>>> copied_list is seq
False

Creation shallow copy means that only the structure of the elements is copied, but not the elements themselves. Both copies of the list share the same instances of individual items.

If you need to duplicate absolutely everything, including elements, then you need to create deep copy of the list (copy.deepcopy(x)). The built-in module in Python comes in handy for this purpose. copy

Key findings

Slices are not only useful for selecting items within a sequence, but can also be used for clearing, reversing, and copying lists.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *