Rodrigo πŸπŸš€ Profile picture
Take your Python 🐍 skills to the next level πŸš€! Daily drop of Python knowledge https://t.co/vBcyYaK8hl πŸπŸ’§

Sep 20, 2021, 10 tweets

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.

Keep scrolling