Next / Previous / Contents / TCC Help System / NM Tech homepage

4. Sequence types

Mathematically, a sequence in Python represents an ordered set.

Sequences are an example of container classes: values that contain other values inside them.

Mutability: You can't change part of an immutable value. For example, you can't change the first character of a string from 'a' to 'b'. It is, however, easy to build a new string out of pieces of other strings.

Type nameContainsExamplesMutable?
str8-bit characters "abc" 'abc' "" '' '\n' '\x00' No
unicode32-bit characters u'abc' u'\u000c' No
listAny values [23, "Fred", 69.8] [] Yes
tupleAny values (23, "Fred", 69.8) () (44,) No

Here are some calculator-mode examples. First, we'll create a string named s, a list named L, and a tuple named t:

>>> s = "abcde"
>>> L = [0, 1, 2, 3, 4, 5]
>>> t = ('x', 'y')
>>> s
'abcde'
>>> L
[0, 1, 2, 3, 4, 5]
>>> t
('x', 'y')

4.1. Functions and operators for sequences

The built-in function len(S) returns the number of elements in a sequence S.

>>> print len(s), len(L), len(t)
5 6 2

Function max(S) returns the largest value in a sequence S, and function min(S) returns the smallest value in a sequence S.

>>> max(L)
5
>>> min(L)
0
>>> max(s)
'e'
>>> min(s)
'a'

To test for set membership, use the “in” operator. For a value v and a sequence S, the expression v in S returns the Boolean value True if there is at least one element of S that equals v; it returns False otherwise.

>>> 2 in L
True
>>> 77 in L
False

There is an inverse operator, v not in S, that returns True if v does not equal any element of S, False otherwise.

>>> 2 not in L
False
>>> 77 not in L
True

The “+” operator is used to concatenate two sequences of the same type.

>>> s + "xyz"
'abcdexyz'
>>> L + L
[0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
>>> t + ('z',)
('x', 'y', 'z')

When the “*” operator occurs between a sequence S and an integer n, you get a new sequence containing n repetitions of the elements of S.

>>> "x" * 5
'xxxxx'
>>> "spam" * 8
'spamspamspamspamspamspamspamspam'
>>> [0, 1] * 3
[0, 1, 0, 1, 0, 1]