Python | tuple() Function

The tuple() function is a built-in function in Python that can be used to create a tuple.

A tuple is an immutable sequence type.

Syntax:

tuple(iterable)  

Parameters: This function accepts a single parameter iterable (optional). It is an iterable(list, range etc..) or an iterator object. If an iterable is passed, the corresponding tuple is created. If the iterable is not passed, empty tuple is created .

Returns: It does not returns any-thing but creates a tuple.



Error and Exception: It returns a TypeError, if an iterable is not passed.

Below programs illustrate tuple() function in Python:
Program 1: Program demonstrating the use of tuple() function

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program demonstrating
# the use of tuple() function
  
# when parameter is not passed
tuple1 = tuple()
print(tuple1)
  
# when an iterable(e.g., list) is passed
list1= [ 1, 2, 3, 4
tuple2 = tuple(list1)
print(tuple2)
  
# when an iterable(e.g., dictionary) is passed
dict = { 1 : 'one', 2 : 'two'
tuple3 = tuple(dict)
print(tuple3)
  
# when an iterable(e.g., string) is passed
string = "geeksforgeeks" 
tuple4 = tuple(string)
print(tuple4)

chevron_right


Output:

()
(1, 2, 3, 4)
(1, 2)
('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')

Program 2: Program demonstrating the TypeError

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program demonstrating 
# the TypeError in tuple() function
  
# Error when a non-iterable is passed
tuple1 = tuple(1
print(tuple1)

chevron_right


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

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.