[Tutor] How does slicing work?

Alan Gauld alan.gauld at btinternet.com
Sat Jun 16 10:32:53 CEST 2012


On 16/06/12 03:48, Kanone Seele wrote:
> Hello,I'm a beginner in python.I found some qustions in Chapter 9's Quiz
> of the book/Learning Python,4th ed/,

There's a bunch of math behind slicing but one of the best descriptions
I found when I was learning Python was to think of the slice action as a 
pair of blades that slice between the list entries. Thus zero is before 
the first entry. -1 is one back from the end - ie the last element. So 
applying that to your examples lets see what we get:


>>>> L = [1, 2, 3, 4]
>
>>>> L[-1000:100]
>
> [1, 2, 3, 4]

One blade 1000 elements back from the end, the other 100 elements 
forward from the beginning. Between the blades we have the whole list...

>>>> L[3:1]
>
> []

First blade in front of the second blade doesn't work. You can only cut 
'backwards' using negative indexes (or the third index argument)
eg:

 >>> L[-3:-1]
[2,3]
 >>> L[3:1:-1]
[4,3]

Back to your examples:

>>>> L[3:1] = ['?']
>>>> L
> [1, 2, 3, '?', 4]


OK, This one is a bit more confusing.
The [3:1] slice above returns an empty slice between 3 and 4.
The assignment operation replaces the slice with the assigned list. So 
in this case we replace the empty slice with the question mark.


Here are some more simple examples working up to yours:


L = [1,2,3,4]
L[:0] = [-1]  # insert before list
L
[-1, 1, 2, 3, 4]
L[-1000:0]=[-2]   # and again
L
[-2, -1, 1, 2, 3, 4]
L[100:]=[5]  # insert after list
L
[-2, -1, 1, 2, 3, 4, 5]
L[3:6] = [6]   # replace multiple members
L
[-2, -1, 1, 6, 5]
L = [1,2,3,4]  # reset list
L[3:3]   # empty slice
[]
L[3:3]=[3.5]   # insert after 3
L
[1, 2, 3, 3.5, 4]
L[3:1]=['?']   # your example is effectively the same
L
[1, 2, 3, '?', 3.5, 4]

HTH,
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list