tuple() Function in Python
The Python tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an ordered and immutable sequence type.
Python tuple() Function Syntax
Syntax: tuple(iterable)
- iterable (optional): It is an iterable(list, range etc..) or an iterator object
- If an iterable is passed, the corresponding tuple is created,
- else, an empty tuple is created.
Return: Returns a Tuple
It raises a TypeError, if an iterable is not passed. Below programs illustrate tuple() function in Python.
Python tuple() Function Example:
Python3
l = [1,2,3]print(tuple(l)) |
Output:
(1, 2, 3)
Example 1: Uses of tuple() in Python
Program demonstrating the use of tuple() function.
Python3
# when parameter is not passedtuple1 = tuple()print("empty tuple:", tuple1)# when an iterable(e.g., list) is passedlist1= [ 1, 2, 3, 4 ]tuple2 = tuple(list1)print("list to tuple:", tuple2)# when an iterable(e.g., dictionary) is passeddict = { 1 : 'one', 2 : 'two' }tuple3 = tuple(dict)print("dict to tuple:", tuple3)# when an iterable(e.g., string) is passedstring = "geeksforgeeks";tuple4 = tuple(string)print("str to tuple:", tuple4) |
Output:
empty tuple: ()
list to tuple: (1, 2, 3, 4)
dict to tuple: (1, 2)
str to tuple: ('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')Example 2: Errors when using Tuple
Program demonstrating the TypeError using tuple()
Python3
# Python3 program demonstrating# the TypeError in tuple() function# Error when a non-iterable is passedtuple1 = tuple(1)print(tuple1) |
Output:
Traceback (most recent call last):
File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in
tuple1=tuple(1)
TypeError: 'int' object is not iterable

