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
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 |
If the iterable is not passed to tuple(), the function creates an empty tuple and returns a TypeError.
Input | Return Value |
---|---|
If iterable | 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)
Output:
tuple1 = () tuple2 = (2, 3, 5) tuple1 = ('P', 'y', 't', 'h', 'o', 'n') tuple1 = (2, 4)
# Error when a non-iterable is passed
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