Sequences and Sets in Python
(Page 1 of 4 )
In this fifth part of a nine-part series on the Python language, you'll learn about sequences, lists, sets, and more. This article is excerpted from chapter four of the book
Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Slicing a sequence
To indicate a subsequence of S , you can use a slicing, with the syntax S[i:j], where i and j are integers. S[i:j] is the subsequence of S from the i th item, included, to the j th item, excluded. In Python, ranges always include the lower bound and exclude the upper bound. A slice is an empty subsequence if j is less than or equal to i , or if i is greater than or equal to L , the length of S . You can omit i if it is equal to 0, so that the slice begins from the start of S. You can omit j if it is greater than or equal to L, so that the slice extends all the way to the end of S. You can even omit both indices, to mean a copy of the entire sequence: S[:]. Either or both indices may be less than 0. A negative index indicates the same spot inS as L+n , just like in indexing. An index greater than or equal to L means the end of S, while a negative index less than or equal to -L means the start of S . Here are some examples:
x = [1, 2, 3, 4]
x[1:3] # [2, 3]
x[1:] # [2, 3, 4]
x[:2] # [1, 2]
Slicing can also use the extended syntax S[i:j:k]. k is the stride of the slice, or the distance between successive indices. S[i:j] is equivalent to S[i:j:1], S[::2] is the subsequence of S that includes all items that have an even index in S , and S[::-1] has the same items as S , but in reverse order.
Strings
String objects are immutable, so attempting to rebind or delete an item or slice of a string raises an exception. The items of a string object (corresponding to each of the characters in the string) are themselves strings, each of length 1. The slices of a string object are also strings. String objects have several methods, which are covered in "Methods of String Objects" on page 186.
Tuples
Tuple objects are immutable, so attempting to rebind or delete an item or slice of a tuple raises an exception. The items of a tuple are arbitrary objects and may be of different types. The slices of a tuple are also tuples. Tuples have no normal (nonspecial) methods, only some of the special methods covered in "Special Methods" on page 104.
Lists
List objects are mutable, so you may rebind or delete items and slices of a list. The items of a list are arbitrary objects and may be of different types. The slices of a list are lists.
Modifying a list
You can modify a list by assigning to an indexing. For instance:
x = [1, 2, 3, 4]
x[1] = 42 # x is now [1, 42, 3, 4]
Another way to modify a list object L is to use a slice of L as the target (LHS) of an assignment statement. The RHS of the assignment must then be an iterable. If the LHS slice is in extended form, then the RHS must have just as many items as the number of items in the LHS slice. However, if the LHS slice is in normal
(nonextended) form, then the LHS slice and the RHS may each be of any length; assigning to a (nonextended) slice of a list can add or remove list items. For example:
x = [1, 2, 3, 4]
x[1:3] = [22, 33, 44] # x is now [1, 22, 33, 44, 4]
x[1:4] = [8, 9] # x is now [1, 8, 9, 4]
Here are some important special cases of assignment to slices:
Using the empty list [] as the RHS expression removes the target slice from L . In other words, L[i:j]=[] has the same effect as del L[i:j].
Using an empty slice of L as the LHS target inserts the items of the RHS at the appropriate spot in L. In other words, L[i:i]=['a','b'] inserts the items 'a' and 'b' before the item that was at index i in L before the assignment.
Using a slice that covers the entire list object,
L[:], as the LHS target totally replaces the contents of L .
You can delete an item or a slice from a list with del. For instance:
x = [1, 2, 3, 4, 5]
del x[1] # x is now [1, 3, 4, 5]
del x[::2] # x is now [3, 5]
In-place operations on a list
List objects define in-place versions of the + and * operators, which you can use via augmented assignment statements. The augmented assignment statement L+=L1 has the effect of adding the items of iterable L1 to the end of L . L*=n has the effect of adding n-1 copies of L to the end of L ; if n<=0, L*=n empties the contents of L, like L[:]=[].
Next: List methods >>
More Python Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Check it out today at your favorite bookstore. Buy this book now.
|
|