Python:Basics:Slices

From Python

Jump to: navigation, search
« Contents
Slices
»
Lists and tuples Dictionaries

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.

Contents

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
1 alphabet = "abcdefghij" Making an alphabet variable.
2 slice1 = alphabet[1:3] Slicing from subscript 1 thru subscript 2.

slice1 = ’bc’
3 slice2 = alphabet[:3]
Slicing from subscript 0 (empty beginIndex) thru subscript 2.

slice2 = ’abc’
4 slice3 = alphabet[1:] Slicing from subscript 1 thru the last subscript (empty endIndex).

slice3 = ’bcdefghij’
5 slice4 = alphabet[:] Slicing from subscript 0 thru the last subscript.

slice4 = ’abcdefghij’
6 slice5 = alphabet[-1:] Slicing from the next-to-last subscript(-1) thru the last subscript.

slice5 = ’j’
7 slice6 = alphabet[:-1] Slicing from subscript 0 thru the nest-to-last subscript.

slice6 = ’abcdefghi’
8 lstFruit = [’apple’,’banana’,’cherry’,’date’] Making a fruit list.
9 lstSlice1 = lstFruit[1:3] Slicing from subscript1 thru subscript 2.

lstSlice1 = [’banana’, ’cherry’]
10 lstFruit2 = lstFruit[:] Slicing from subscript 0 thru the last subscript. This makes a copy, not a reference of lstFruit.
11 lstFruit2[1] = ’blueberry’ Changing lstFruit2 does not change lstFruit.
12 lstFruit3 = lstFruit Copying lstFruit to lstFruit3.
Changing lstFruit3 does change lstFruit.

Best Practices for Slices

Self-Test Questions

NA

Review Questions

NA

« Contents
Slices
»
Lists and tuples Dictionaries
Personal tools