Python Tuples PDF
Python Tuples PDF
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only
one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements.
You are able to take portions of existing tuples to create new tuples as the following example
demonstrates −
#!/usr/bin/python
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
print tup
del tup;
print "After deleting tup : "
print tup
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more −
In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter −
len(1, 2, 3) 3 Length
1, 2, 3 + 4, 5, 6 1, 2, 3, 4, 5, 6 Concatenation
′ Hi! ′ , *4 ′ Hi! ′ , ′ Hi! ′ , ′ Hi! ′ , ′ Hi! ′ Repetition
3 in 1, 2, 3 True Membership
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets
for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −
#!/usr/bin/python
1
cmptuple1, tuple2
2
lentuple
3
maxtuple
4
mintuple
5
tupleseq
Loading [MathJax]/jax/output/HTML-CSS/jax.js