A few words about Python’s extended slices

One thing that most Python users learn at the very beginning are list slices – defining a part of the list using the samplelist[begin:end] syntax. It’s great thing, but – surprisingly – many people don’t even know, that there’s different syntaxt for this, containing one additional parameter – “step”: samplelist[begin:end:step]. How does it work?

The base idea of using “step” is to pick only the every n-th element of the list. For example (list will stay the same for other examples):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [1]: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
In [2]: a[::1]
Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
In [3]: a[::2]
Out[3]: [1, 3, 5, 7, 9]
 
In [4]: a[::3]
Out[4]: [1, 4, 7, 10]
 
In [5]: a[::4]
Out[5]: [1, 5, 9]
 
In [6]: a[::5]
Out[6]: [1, 6]

So, as you may notice, when start is not defined, it always starts from first element (start, which is 0 by default) and then adds “step” to current index, picks element and makes this index current, unless it iterates throught the whole list.

Of course it works with begin/end provided, for example:

1
2
In [2]: a[3:7:2]
Out[2]: [4, 6]

Step can be negative too:

1
2
3
4
5
6
7
8
9
10
In [1]: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
In [2]: a[::-1]
Out[2]: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
 
In [3]: a[::-2]
Out[3]: [10, 8, 6, 4, 2]
 
In [4]: a[::-3]
Out[4]: [10, 7, 4, 1]

Analogously, it starts from the last element (end, which is -1) and picks elements in reversed order. But watch out – if you want to provide negative step with begin and end parameters provided it won’t work as you may expect. Order of the begin and end elements have to be reversed or provided as negative ones:

1
2
3
4
5
6
7
8
In [5]: a[3:7:-2]
Out[5]: []
 
In [6]: a[7:3:-2]
Out[6]: [8, 6]
 
In [7]: a[-3:-7:-2]
Out[7]: [8, 6]

That’s basically all about this topic. So, is it useful? I think yes, but not very often. Honestly, I do not use extended slices very often when working with list. Instead of this, my favourite use case for this is reversing a string, which I also described it one of the previous articles:

1
2
3
4
In [1]: s = "abcdefg"
 
In [2]: s[::-1]
Out[2]: 'gfedcba'

Anyway, I think it’s good to know that such feature exists.

Comments are closed.