Python tuple() Function
The Python tuple() function (or tuple() constructor) is used to create tuple using an iterable object. An iterable object can be any data structure like list, tuple, set, string, dictionary and range iterable.
Syntax
tuple(iterable)
Parameters
iterable |
Required. iterable like list, tuple, set, string , dictionary and range() etc. |
Example:
In the example below, tuple() function is used to create tuple using a given iterable.
#using list iterable MyTuple = tuple(['JAN', 'FEB', 'MAR', 'APR']) print(MyTuple) #using tuple iterable MyTuple = tuple(('JAN', 'FEB', 'MAR', 'APR')) print(MyTuple) #using string iterable MyTuple = tuple('string') print(MyTuple) #using range iterable MyTuple = tuple(range(1,6)) print(MyTuple)
The output of the above code will be:
('JAN', 'FEB', 'MAR', 'APR') ('JAN', 'FEB', 'MAR', 'APR') ('s', 't', 'r', 'i', 'n', 'g') (1, 2, 3, 4, 5)
Example: using dictionary iterable
In the example below, tuple() function is used to create tuple from a given dictionary.
MyDict = { 'name': 'John', 'age': 25, 'city': 'London' } MyTuple = tuple(MyDict) print(MyTuple) MyTuple = tuple(MyDict.keys()) print(MyTuple) MyTuple = tuple(MyDict.values()) print(MyTuple)
The output of the above code will be:
('name', 'age', 'city') ('name', 'age', 'city') ('John', 25, 'London')
❮ Python Built-in Functions