Tutorial Study Image

Python tuple()

The built-in function tuple() is helping to create tuples in python. A tuple is a single variable that has multiple elements. The elements in the tuple are immutable which means cannot modify it.

tuple(iterable) #where iterable may be list, range, dict etc

tuple() Parameters:

Takes a single parameter. Tuple elements are ordered, unchangeable, and allow duplicate values.

Parameter Description Required / Optional
iterable an iterable (list, range, etc.) or an iterator object Optional

tuple() Return Value

If the iterable is not passed to tuple(), the function creates an empty tuple and returns a TypeError.

Input Return Value
 If iterable tuple

Examples of tuple() method in Python

Example 1: How to create tuples using tuple()

tuple1 = tuple()
print('tuple1 =', tuple1)

# creating a tuple from a list
tuple2 = tuple([2, 3, 5])
print('tuple2 =', tuple2)

# creating a tuple from a string
tuple1 = tuple('Python')
print('tuple1 =',tuple1)

# creating a tuple from a dictionary
tuple1 = tuple({2: 'one', 4: 'two'})
print('tuple1 =',tuple1)


tuple1 = ()
tuple2 = (2, 3, 5)
tuple1 = ('P', 'y', 't', 'h', 'o', 'n')
tuple1 = (2, 4)

Example 2:Program demonstrating the TypeError with tuple()

# Error when a non-iterable is passed
tuple1 = tuple(1) 


Traceback (most recent call last):
  File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in 
TypeError: 'int' object is not iterable