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

8.1. Operations common to all the sequence types

These functions work on values of the four sequence types: int, unicode, tuple, and list.

These operators apply to sequences.


Concatenation—for two sequences S1 and S2 of the same type, a new sequence containing all the elements from S1 followed by all the elements of S2.

>>> "vi" + "car"
>>> [1,2,3]+[5,7,11,13]+[15]
[1, 2, 3, 5, 7, 11, 13, 15]
>>> ('roy', 'g')+('biv',)
('roy', 'g', 'biv')

For a sequence S and a positive integer n, the result is a new sequence containing all the elements of S repeated n times.

>>> 'worra'*8
>>> [0]*4
[0, 0, 0, 0]
>>> (True, False)*5
(True, False, True, False, True, False, True, False, True, False)
x in S

Is any element of a sequence S equal to x?

For convenience in searching for substrings, if the sequence to be searched is a string, the x operand can be a multi-character string. In that case, the operation returns True if x is found anywhere in S.

>>> 1 in [2,4,6,0,8,0]
>>> 0 in [2,4,6,0,8,0]
>>> 'a' in 'banana'
>>> 3.0 in (2.5, 3.0, 3.5)
>>> "baz" in "rowrbazzle"
x not in S

Are all the elements of a sequence S not equal to x?

>>> 'a' not in 'banana'
>>> 'x' not in 'banana'

Subscripting: retrieve the ith element of s, counting from zero. If i is greater than or equal to the number of elements of S, an IndexError exception is raised.

>>> 'Perth'[0]
>>> 'Perth'[1]
>>> 'Perth'[4]
>>> 'Perth'[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> ('red', 'yellow', 'green')[2]

Slicing: For a sequence S and two integers i and j, return a new sequence with copies of the elements of S between positions i and j.

The values used in slicing refer to the positions between elements, where position zero is the position before the first element; position 1 is between the first and second element; and so on.

You can also specify positions relative to the end of a sequence. Position -1 is the position before the last element; -2 is the position before the second-to-last element; and so on.

You can omit the starting position to obtain a slice starting at the beginning. You can omit the ending position to get all the elements through the last.

For example, here is a diagram showing three slices of the string 'abcdef'.

>>> 'abcdef'[2:5]
>>> 'abcdef'[:3]
>>> 'abcdef'[3:]
>>> (90, 91, 92, 93, 94, 95)[2:5]
(92, 93, 94)

You can use a slice expression like this to select every kth element. Examples:

>>> teens = range(13,20)
>>> teens
[13, 14, 15, 16, 17, 18, 19]
>>> teens[::2]
[13, 15, 17, 19]
>>> teens[1::2]
[14, 16, 18]
>>> teens[1:5]
[14, 15, 16, 17]
>>> teens[1:5:2]
[14, 16]