There are three standard sequence operations (+,
*, []) that can be performed with
tuples as well as lists
and strings.
The + operator creates a new
tuple as the concatenation of the arguments.
Here's an example.
>>>
("chapter",8) + ("strings","tuples","lists")
('chapter', 8, 'strings', 'tuples', 'lists')
The * operator between tuples
and numbers (number * tuple or
tuple * number) creates a new
tuple that is a number of repetitions of the
input tuple.
>>>
2*(3,"blind","mice")
(3, 'blind', 'mice', 3, 'blind', 'mice')
The [] operator selects an item or a slice from the
tuple. There are two forms. The first format is
tuple
[
index
]
. Items are numbered from 0
at beginning through the length. They are also number from -1 at the end
backwards to
-len(
tuple
).
The slice format is
tuple
[
start
:
end
]
. Elements from
start
to
end
-1 are chosen; there will be
end
−
start
elements in the
resulting tuple. If
start
is omitted, it is the beginning of the
tuple (position 0), if
end
is omitted, it is the end of the tuple
(position -1).
>>>
t=( (2,3), (2,"hi"), (3,"mom"), 2+3j, 6.02E23 )
>>>
t[2]
(3, 'mom')
>>>
print t[:3], 'and', t[3:]
((2, 3), (2, 'hi'), (3, 'mom')) and ((2+3j), 6.02e+23)
>>>
print t[-1], 'then', t[-3:]
6.02e+23 then ((3, 'mom'), (2+3j), 6.02e+23)