Tuple & Sort
Tuple & Sort
Introduction
A tuple in Python is much like a list except that it is immutable
(unchangeable) once created.ie the values that you give it first,
are the values that you are stuck with for the rest of the program
and tuples use parentheses and lists use square brackets.
Example:
List1 = [1, 'a', [6, 3.14]] is a list.
Tuple1 = (1, 'a', [6, 3.14]) is a tuple.
Creating Tuples
Creating a tuple is as simple as putting different comma-
separated values and optionally you can put these comma-
separated values between parentheses also.
For example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
Example:1
#!/usr/bin/python
Example:2
#!/usr/bin/python
months = ('January','February','March','April','May','June',
'July','August','September','October','November','December')
Updating Tuples
Tuples are immutable which means you cannot update them or
change values of tuple elements. But we able able to take
portions of an existing tuples to create a new tuples as follows:
Example:
#!/usr/bin/python
print tup;
del tup;
print "After deleting tup : "
print tup;
An exception raised, this is because after del tup tuple does not
exist anymore:
Tuples have no methods
You can't add elements to a tuple. Tuples have no append or
extend method.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.append("new")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'
method.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.index("example")
Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'
tuple.
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> "z" in t
1
Conversions
Convert list to tuples using the built in tuple() method.
>>> l = [4, 5, 6]
>>> tuple(l)
(4, 5, 6)
Sorting Tuple
The following program shows you how to sort a tuple.
Exercise Problems: