The Wayback Machine - https://web.archive.org/web/20230512160719/https://www.geeksforgeeks.org/python-tuple-function/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

tuple() Function in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 passed
tuple1 = tuple()
print("empty tuple:", tuple1)
 
# when an iterable(e.g., list) is passed
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
print("list to tuple:", tuple2)
 
# when an iterable(e.g., dictionary) is passed
dict = { 1 : 'one', 2 : 'two' }
tuple3 = tuple(dict)
print("dict to tuple:", tuple3)
 
# when an iterable(e.g., string) is passed
string = "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 passed
tuple1 = 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

My Personal Notes arrow_drop_up
Last Updated : 03 Aug, 2022
Like Article
Save Article
Similar Reads
Related Tutorials