5.5 Sequence Slicing

  • Can slice sequences to create new sequences of the same type containing subsets of the original elements.
  • Slice operations that do not modify a sequence work identically for lists, tuples and strings.

Specifying a Slice with Starting and Ending Indices

In [1]:
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
In [2]:
numbers[2:6]
Out[2]:
[5, 7, 11, 13]

Specifying a Slice with Only an Ending Index

  • Starting index 0 is assumed.
In [3]:
numbers[:6]
Out[3]:
[2, 3, 5, 7, 11, 13]
In [4]:
numbers[0:6]
Out[4]:
[2, 3, 5, 7, 11, 13]

Specifying a Slice with Only a Starting Index

  • Assumes the sequence's length as the ending index.
In [5]:
numbers[6:]
Out[5]:
[17, 19]
In [6]:
numbers[6:len(numbers)]
Out[6]:
[17, 19]

Specifying a Slice with No Indices

In [7]:
numbers[:]
Out[7]:
[2, 3, 5, 7, 11, 13, 17, 19]
  • Though slices create new objects, slices make shallow copies of the elements.
  • In the snippet above, the new list’s elements refer to the same objects as the original list’s elements.

Slicing with Steps

In [8]:
numbers[::2]
Out[8]:
[2, 5, 11, 17]

Slicing with Negative Indices and Steps

In [9]:
numbers[::-1]
Out[9]:
[19, 17, 13, 11, 7, 5, 3, 2]
In [10]:
numbers[-1:-9:-1]
Out[10]:
[19, 17, 13, 11, 7, 5, 3, 2]

Modifying Lists Via Slices

  • Can modify a list by assigning to a slice.
In [11]:
numbers[0:3] = ['two', 'three', 'five']
In [12]:
numbers
Out[12]:
['two', 'three', 'five', 7, 11, 13, 17, 19]
In [13]:
numbers[0:3] = []
In [14]:
numbers
Out[14]:
[7, 11, 13, 17, 19]
In [15]:
numbers = [2, 3, 5, 7, 11, 13, 17, 19]
In [16]:
numbers[::2] = [100, 100, 100, 100]
In [17]:
numbers
Out[17]:
[100, 3, 100, 7, 100, 13, 100, 19]
In [18]:
id(numbers)
Out[18]:
4391419592
In [19]:
numbers[:] = []
In [20]:
numbers
Out[20]:
[]
In [21]:
id(numbers)
Out[21]:
4391419592
  • Deleting numbers’ contents is different from assigning numbers a new empty list [].
  • Identities are different, so they represent separate objects in memory.
In [22]:
numbers = []
In [23]:
numbers
Out[23]:
[]
In [24]:
id(numbers)
Out[24]:
4391542152
  • When you assign a new object to a variable, the original object will be garbage collected if no other variables refer to it.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.