Python tuple() function

The tuple() function in Python returns a 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 tuples, refer to their separate post.

Python tuple() function syntax

The syntax of the 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 an empty tuple. An iterable may be a list, dictionary, etc.

Note: When a dictionary is used as an iterable, then its key will be used.

Python tuple() function example

Here is an example of the 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')

Advantages of the tuple() function in Python

Disadvantages of the tuple() function in Python

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!