These functions work on values of the four sequence
These operators apply to sequences.
Concatenation—for two sequences
of the same type, a new sequence containing all the
all the elements of
>>> "vi" + "car" 'vicar' >>> [1,2,3]+[5,7,11,13]+ [1, 2, 3, 5, 7, 11, 13, 15] >>> ('roy', 'g')+('biv',) ('roy', 'g', 'biv')
For a sequence
and a positive integer
, the result
is a new sequence containing all the elements of
>>> 'worra'*8 'worraworraworraworraworraworraworraworra' >>> *4 [0, 0, 0, 0] >>> (True, False)*5 (True, False, True, False, True, False, True, False, True, False)
Is any element of a sequence
For convenience in searching for substrings, if the
sequence to be searched is a string, the
operand can be a
multi-character string. In that case, the operation
is found anywhere in
>>> 1 in [2,4,6,0,8,0] False >>> 0 in [2,4,6,0,8,0] True >>> 'a' in 'banana' True >>> 3.0 in (2.5, 3.0, 3.5) True >>> "baz" in "rowrbazzle" True
Are all the elements of a sequence
>>> 'a' not in 'banana' False >>> 'x' not in 'banana' True
Subscripting: retrieve the
th element of
, counting from zero. If
than or equal to the number of elements of
IndexError exception is raised.
>>> 'Perth' 'P' >>> 'Perth' 'e' >>> 'Perth' 'h' >>> 'Perth' Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range >>> ('red', 'yellow', 'green') 'green'
Slicing: For a sequence
and two integers
, return a
new sequence with copies of the elements of
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'[2:5] 'cde' >>> 'abcdef'[:3] 'abc' >>> 'abcdef'[3:] 'def' >>> (90, 91, 92, 93, 94, 95)[2:5] (92, 93, 94)
You can use a slice expression like this to select
th 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]