On Slicing Python Lists
2 June 2016
A lot many are familiar with Python lists and the feature of slicing, although I find the description that most tutorials not intuitive enough. Here is how it goes.
Let us start with defining an array of 10 elements
>>> a = [i for i in range(10)]
Now, the following I assume you're familiar with.
>>> a[3:6]
[3, 4, 5]
And the way people think about it is selecting elements starting with index 3 till and including the element with index 6-1=5.
Do you digest that? I cannot. Why do I include the first index while not the second one? If I think in terms of indices, I have to spend my brain power in subtracting the second index by one, and I tell you I am very lazy about that.
Then there are people who say that you start with index 3 and choose 6-3=3 elements there on. This does work because we see the following happening.
>>> a[4:4]
[]
But I do not understand that if I were inventing slicing, and I would want people to think in terms of an index and a length, why would I not just keep length as the second parameter? In this hypothetical situation,
>>> a[3:3]
[3, 4, 5]
DISCLAIMER: I do not claimer that this is how it went but I'll now talk about how I like to look at slicing
>>> a[3:]
[3, 4, 5, 6, 7, 8, 9]
I like to say that doing this skips the first three elements and gives the rest.
>>> a[:6]
[0, 1, 2, 3, 4, 5]
And this picks the first six elements. Simple really!
>>> a[3:6]
[3, 4, 5]
This just gives the intersection of the two.
My two cents.
Get new posts by email
दक्षिणा (Tip)
Money is not real, but your support towards maintaining this body and mind is valuable.