Python tuple() Function

The tuple() function in Python returns tuple object. Basically this function is used to create tuples in Python. For example:

x = [12, 32, 543]
y = tuple(x)
print(type(y))

a = tuple([12, 43, 453])
print(type(a))

b = tuple(["codes", "cracker", "dot", "com"])
print(type(b))

The output is:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

Note - To learn in detail about tupleTuple, refer to its separate tutorial.

Python tuple() Function Syntax

The syntax of tuple() function in Python, is:

tuple(iterable)

The iterable parameter is optional. Means that if no iterable is specified, tuple() returns a tuple object, of course, but empty tuple. An iteratable may be a list, dictionary etc.

Note - When dictionary is used as iterable, then its key will be used.

Python tuple() Function Example

Here is an example of tuple() function in Python:

x = [1, 2, 3, 5]
a = tuple(x)
print(a)

x = "Python Programming"
a = tuple(x)
print(a)

x = {"Day": "Sun", "Month": "Dec"}
a = tuple(x)
print(a)

The output is:

(1, 2, 3, 5)
('P', 'y', 't', 'h', 'o', 'n', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')
('Day', 'Month')

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋