Understanding Programming with Python:Python Basics:Slices

From Python

Jump to: navigation, search

Slices are one of the dandy features of Python. Other languages go into great contortions to extract a part of a string or a list. Python makes it easy.

Slices in the Real World

We use the word slice often in the real world. Let’s look at a real world slice and then apply that understanding to programming.

Imagine a loaf of bread with a delicious-looking nut/date topping. The topping is centered in the middle of the loaf, however. No problem for you. You go to the center of the loaf and extract several slices from the middle. Then you put the loaf back together before anyone else can see you. The loaf looks just like it did before, minus the slices that you extracted.

Python uses the term slice for the same operations as a real world slice. When you want to extract part of a string, or some part of a list, you use a slice. Other languages use the term substring for a string slice, and may have no mechanism for extract a list slice. Python’s slice syntax is easy and elegant:

slicedString = aString[beginIndex:endIndex]

slicedList = aList[beginIndex:endIndex]

Slices Examples
Line Code Meaning
  alphabet = "abcdefghij"

slice1 = alphabet[1:3]

slice2 = alphabet[:3]

slice3 = alphabet[1:]

slice4 = alphabet[:]

slice5 = alphabet[-1:]

slice6 = alphabet[:-1]

lstFruit = [’apple’,’banana’,’cherry’,’date’]

lstSlice1 = lstFruit[1:3]

lstFruit2 = lstFruit[:]

lstFruit2[1] = ’blueberry’

lstFruit3 = lstFruit
lstFruit3[1] = ’blueberry’
Making an alphabet variable.

Slicing from subscript 1 thru subscript 2.

slice1 = ’bc’

Slicing from subscript 0 (empty beginIndex) thru subscript 2.

slice2 = ’abc’

Slicing from subscript 1 thru the last subscript (empty endIndex).

slice3 = ’bcdefghij’

Slicing from subscript 0 thru the last subscript.

slice4 = ’abcdefghij’

Slicing from the next-to-last subscript(-1) thru the last subscript.

slice5 = ’j’

Slicing from subscript 0 thru the nest-to-last subscript.

slice6 = ’abcdefghi’
[’banana’, ’cherry’]

Making a fruit list.

Slicing from subscript1 thru subscript 2.

lstSlice1 = [’banana’, ’cherry’]

Slicing from subscript 0 thru the last subscript. This makes a copy, not a reference of lstFruit.

Changing lstFruit2 does not change lstFruit.

Copying lstFruit to lstFruit3.
Changing lstFruit3 does change lstFruit.

Precepts and Practices for Slices

Personal tools