Are you a master of Python π sequence slicing?
Here is a short thread π§΅ covering four idiomatic slicing patterns that you could get used to.
These four patterns are great because they have a clear interpretation of what they do.
Here we go ππ§΅
π s[n:]
If `n β₯ 0`, then `s[n:]` means
π βSkip the first `n` elements.β
β If `n` is 0, then we skip 0 elements, which is another way of saying we get all of them.
That's the same as `s[:]`.
π s[-n:]
If `n > 0`, then `s[-n:]` means
π βThe last `n` elements.β
β -0 and 0 are the same, so `s[-0:]` gets all the sequence, like above.
π s[:n]
If `n β₯ 0`, then `s[:n]` means
π βThe first `n` elements.β
β If `n` is 0, the last 0 elements means no elements at all, and we get an empty sequence.
π s[:-n]
If `n > 0`, then `s[:-n]` means
π βDrop the last `n` elements.β
β Again, careful with 0 and -0! s[:-0] returns an empty sequence, because of the case above.
Here are some βexercisesβ to make sure you understood how these sequence slicing patterns really work:
β There's an interesting caveat to slicing that you should be aware of.
Slicing works, even if the indices used are too large for the sequence in question.
For example, `s[10:]` means βskip the first 10 elementsβ.
If `s` has only 5 elements, then we get an empty sequence:
β β The βcaveat of the caveatβ is that this does NOT change the interpretation of the slicing patterns we just saw.
If I have 5 elements and ignore the first 10, of course there is nothing left to look at.
It's just important to note that slicing does not do any length checks.
There is much more to sequence slicing than this short thread covered!
Do you want to learn even more? πͺπ₯
If you want to learn even more, check out the article from which I drew this content:
mathspp.com/blog/pydonts/iβ¦
I hope this thread was useful!
If it was, follow me (@mathsppblog) for more content like this and retweet the first thread so that everyone can learn proper slicing patterns!
Got any thoughts? ππ¬
See you around π
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.