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.
Similar to List, Tuple is a sequence of values. The values can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Syntactically, a tuple is a comma-separated list of values:
>>>message= 'h','a','i' >>> type(message) <type 'tuple'>
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> message= ('h','a','i') >>> type(message) <type 'tuple'>
To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a', >>> type(t1) <class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a') >>> type(t2) <class 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
>>> t = tuple() >>> t ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence:
>>> course=tuple('python') >>> course ('p', 'y', 't', 'h', 'o', 'n')
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:
>>> temp = a >>> a = b >>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. The number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:
>>> email='[email protected]' >>> username,domain=email.split('@')
The return value from split is a list with two elements; the first element is assigned to username, the second to domain.
>>> username 'hodcse' >>> domain 'aimtocode.com'
A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values.
For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.
The built-in function divmod
takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3) >>> t (2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
Here is an example of a function that returns a tuple:
def min_max(t): return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values.
>>> quot 2 >>> rem 1
Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple.
For example, display all takes any number of arguments and prints them:
>>> def displayall(*args): print(args)
The gather parameter can have any name you like, but args is conventional.
Here‘s how the function works:
>>> displayall('python',355.50,3) ('python', 355.5, 3)
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator.
For example, divmod takes exactly two arguments; it doesn‘t work with a tuple:
>>> t = (7, 3) >>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
But if you scatter the tuple, it works:
>>> divmod(*t) (2, 1)
Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments:
>>> max(55,72,38) 72
But sum does not.
>>> sum(1, 2, 3)
TypeError: sum expected at most 2 arguments, got 3
zip is a built-in function that takes two or more sequences and returns a list of tuples where each tuple contains one element from each sequence.
The name of the function refers to a zipper, which joins and interleaves two rows of teeth.
This example zips a string and a list:
>>> s='hai' >>> t=[0,1,2] >>> zip(s,t) [('h', 0), ('a', 1), ('i', 2)]
The result is a zip object that knows how to iterate through the pairs. The most common use of zip is in a for loop:
>>> for pair in zip(s, t): print(pair) ('h', 0) ('a', 1) ('i', 2)
A zip object is a kind of iterator, which is any object that iterates through a sequence. Iterators are similar to lists in some ways, but unlike lists, you can‘t use an index to select an element from an iterator.
Python includes the following tuple functions −
Sr.No. | Function & Description |
---|---|
1 | cmp(tuple1, tuple2)
Compares elements of both tuples. |
2 | len(tuple)
Gives the total length of the tuple. |
3 | max(tuple)
Returns item from the tuple with max value. |
4 | min(tuple)
Returns item from the tuple with min value. |
5 | tuple(seq)
Converts a list into tuple. |
Method | Description |
---|---|
Python Tuple count() | returns occurrences of element in a tuple |
Python Tuple index() | returns smallest index of element in tuple |
Python any() | Checks if any Element of an Iterable is True |
Python all() | returns true when all elements in iterable is true |
Python ascii() | Returns String Containing Printable Representation |
Python bool() | Converts a Value to Boolean |
Python enumerate() | Returns an Enumerate Object |
Python filter() | constructs iterator from elements which are true |
Python iter() | returns iterator for an object |
Python len() | Returns Length of an Object |
Python max() | returns largest element |
Python min() | returns smallest element |
Python map() | Applies Function and Returns a List |
Python reversed() | returns reversed iterator of a sequence |
Python slice() | creates a slice object specified by range() |
Python sorted() | returns sorted list from a given iterable |
Python sum() | Add items of an Iterable |
Python tuple() Function | Creates a Tuple |
Python zip() | Returns an Iterator of Tuples |