tuple is an important build-in python data
structure type. It is an ordered and immutable serial
How to declare a tuple
We can use the below statement to declare a
tuple
tuple_name
= (elements1,element2,) # this is call
pack
tuple_name
= tuple (serial)
how to visit the elements in tuple:
tuple elements can be visited by index, the
index is started with 0, if the index is beyound the length, the statement will
generate an error
sample code:
>>> tuple_name=tuple("this is
a test")
>>> print tuple_name
('t', 'h', 'i', 's', ' ', 'i', 's', ' ',
'a', ' ', 't', 'e', 's', 't')
>>> tuple_name[5]
'i'
>>> tuple_name[500]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
An interesting and powerful featuer is
using minus index, minus index is the index counting from the end of the tuple.
For example still with the above sample
>>> tuple_name[-1]
't'
>>> tuple_name[-3]
'e'
Unpack the tuple
When tuple is used as right element by
assignment, it can be unpacked.
See below
>>> mytuple=[1,2,3,]
>>> a, b, c = mytuple
then a will be 1, b will be 2 and c will be
3. the length of the elements should be exactly the same as the length of the
tuple
Slice: get the sub-tuple
We can get the sub-tuple by using slice,
the format is tuple[first:last:step]
- First: the first element index for the slice (by default is the 0 if not specified)
- Last: the last element index for the slice(exclusive) (by default is the length of the tuple if not specified)
- Step: the step length (by default is 1)
Some sample
Mytuple[1:5] : from the 2nd to 4th
element
Mytuple[10:] : from the 10th to
last elment
Mytuple[::2] : every other elment
tuple Traversal
Traversal is usually done by the index. We need
to build-in functions len () and range ().
Sample code:
for index in range(len(mytuple)):
dosomething(mytuple[index])
No comments:
Post a Comment