Python | tuple () function

Python Methods and Functions

A tuple is a immutable sequence type .

Syntax :

 tuple (iterable) 

Parameters: This function takes a iteration of a single (optional) parameter. It is an iterative object (list, range, etc.) or an iterator. If an iteration is passed, the corresponding tuple is created. If no iteration is passed, an empty tuple is created.

Returns: returns nothing, but creates a tuple.

Error and Exception: returns TypeError if no iteration is passed.

The following programs illustrate the tuple () function in Python:
Program 1: A program that demonstrates using the tuple () function

# Python3 program demonstrating
# using the tuple () function

 
# when no parameter is passed

tuple1 = tuple ( )

print (tuple1)

  
# when an iteration is passed (eg a list)

list1 = [ 1 , 2 , 3 , 4

tuple2 = tuple (list1)

print (tuple2)

  
# when an iteration is passed (eg a dictionary)

dict = { 1 : 'one ' , 2 : 'two'

tuple3 = tuple ( dict )

print (tuple3)

  
# when an iteration is passed (eg a string)

string = "pythonengineering"  

tuple4 = tuple (string)

print (tuple4)

Output:

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

Program 2: Program showing TypeError

# Python3 program demonstrating
# Type error in tuple () function

 
# Error missing non-repeatable

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