The Tuple() Built-in Function In Python

Overview:

  • In Python the tuple() constructor is presented as one of the built-in functions. The tuple() constructor takes any iterable object as the parameter and creates a tuple containing the elements from the iterable.
  • Note that, tuples can also be created using a pair of parentheses similar to the way lists are created using a pair of square brackets. However, the later way of creating tuples returns a tuple, only when the individual members are passed in. When an iterable is passed, it returns a new iterbale of the same type, not a tuple(as of Python 3.11.1).

Example:

#Example Python program that creates tuples
#using the built-in function tuple(), which is nothing but
#the tuple constructor

# Construct tuple from a list of colors
primaryColors = tuple(["Red", "Green", "Blue"])
print(primaryColors)
print(type(primaryColors))

# Construct tuple from a set of fruits
citrusFruits = tuple({"Lemon", "Orange", "Grapefruit"})
print(citrusFruits)
print(type(citrusFruits))

# Constructs an empty tuple
twoCenturyOldPeople = tuple()
print(twoCenturyOldPeople)

Output:

('Red', 'Green', 'Blue')
<class 'tuple'>
('Orange', 'Lemon', 'Grapefruit')
<class 'tuple'>
()

 


Copyright 2023 © pythontic.com