AlphaCodingSkills

Python - tuple() Function


Advertisements

The 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 and dictionary etc. An iterable created by range() function can also be used here.

Syntax


tuple(iterable)

Parameters

iterable Required. iterable like list, tuple, set, string , dictionary, etc.

Example: Create tuple using an iterable

In the below example, tuple() function is used to create a tuple using an iterable like list, tuple, set and string, etc.

#using list as iterable
MyTuple = tuple(['JAN', 'FEB', 'MAR', 'APR'])
print(MyTuple)

#using tuple as iterable
MyTuple = tuple(('JAN', 'FEB', 'MAR', 'APR'))
print(MyTuple)

#using set as iterable
MyTuple = tuple({'JAN', 'FEB', 'MAR', 'APR'})
print(MyTuple)

#using string as iterable
MyTuple = tuple('string')
print(MyTuple)

Output

('JAN', 'FEB', 'MAR', 'APR')

('JAN', 'FEB', 'MAR', 'APR')

('JAN', 'FEB', 'MAR', 'APR')

('s', 't', 'r', 'i', 'n', 'g')

Example: Create tuple using dictionary as an iterable

In the below example, tuple() function is used to create a tuple using dictionary as an iterable.

MyDict = {
  'name': 'John',
  'age': 25,
  'city': 'London'
}
MyTuple = tuple(MyDict)
print(MyTuple)

MyTuple = tuple(MyDict.keys())
print(MyTuple)

MyTuple = tuple(MyDict.values())
print(MyTuple)

Output

('name', 'age', 'city')

('name', 'age', 'city')

('London', 25, 'John')

Tuples Methods