If you touch Python to some extent, you may see the word slice, but I think that you can understand it because you use it often, but it was actually quite complicated, so I wrote it as an article.
A slice is a syntax (?) That allows you to partially easily access the elements of a sequence.
Slice operations are available in commonly used types such as list and str, so knowing the slices can be quite useful.
Use it like a [Start position: End position].
For example
a = [1, 2, 3, 4, 5]
print(a[0: 4])
print(a[: 4])
print(a[-3:])
print(a[2: -1])
>>>
[1, 2, 3, 4]
[1, 2, 3, 4]
[3, 4, 5]
[3, 4]
It's like this. If you do not enter anything at the start position, it will be processed as 0, and if you do not enter anything at the end position, it will be processed as the end, so it is better not to write in such a case.
It may be a little confusing if there is a minus, but if you use this, you can easily specify the list and the end, so if you get used to it, the world will change (I think it's a bit exaggerated).
Up to this point, I knew the slices, but in reality there was a more complicated way of writing ...!
a [Start position: End position: Slice increment].
By specifying the slice increment, you can "get the element every nth".
For example
a = [1, 2, 3, 4, 5]
print(a[:: 2])
print(a[1:: 2])
print(a[::-1])
print(a[1::-1])
>>>
[1, 3, 5]
[2, 4]
[5, 4, 3, 2, 1]
[2, 1]
is. This is what it is. It's complicated, but it would be nice if you could master it! Especially -1 seems to be quite usable.
However, if you combine these three, it will take some time to understand, maybe. When I reviewed the program I made earlier, I was like, "What? What will happen to this?"
I don't know if it's good to think about readability, but I think it's worth knowing.
That's why it was a story that slices are also deep.
Recommended Posts