Introduction to Tuples

Tuple is a sequence f values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
Syntactically, a tuple is a comma separated list of values:
>>> t ='a','b', 'c', 'd','e'
>>> t
('a', 'b', 'c', 'd', 'e')
>>> type(t)
< type 'tuple'>
To create a tuple with a single element, you have to include comma after final element.
>>> t1 = ('a',)
>>> print t1
('a',)
>>> type(t1)

Without that final comma in parenthesis the Python would treat this declaration as a string.
>>> t1 = ('a')
>>> type(t1)

Another way to create a tuple is with using the built-in function tuple. With no argument, this function will create an empty tuple.
>>> t1 = tuple()
>>> type(t1)

If the argument is a sequence (string, list or tuple), the result of the call to tuple is tuple with the elements of a sequence:
>>> word = tuple('Python is awesome')
>>> print word
('P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', 'w', 'e', 's', 'o', 'm','e')
Because tuple is a name of constructor, you should avoid using it as a variable name. Most list operators also work on tuples. The bracket operator indexes an element:
>>> z = ('a', 'b', 'c', 'd')
>>> print z[0]
a
>>> print z[1]
b
>>> i = 0
>>> while i < len(z):
...       print z[i]
...       i = i + 1
...
a
b
c
d
And the slice operator selects a range of elements:
>>> z[1:3]
('b', 'c')
If you try to modify one of the tuples elements the TypeError exception will occur.
>>> z[0] = 'a'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
You can modify the elements of a tuple, but you can replace one tuple with another.
>>> z = ('Z',) + z[1:]
>>> print z
('Z', 'b', 'c', 'd')

1 komentar: