Python tuple() Function
The Python tuple() function is used to create a tuple, which is a collection of ordered and immutable (unchangeable) elements. This collection can include a variety of data types such as numbers, strings, or even other tuples.
A tuple is similar to a list, but the main difference is that once you create a tuple, you cannot modify its elements i.e. you cannot add, remove, or change them.
Syntax
Following is the syntax of Python tuple() function β
tuple(iterable)
Parameters
This function accepts any iterable object like a list, string, set, or another tuple as a parameter.
Return Value
This function returns a new tuple object with the elements from the given iterable.
Example 1
In the following example, we are using the tuple() function to convert the list "[1, 2, 3]" into a tuple β
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print('The tuple object obtained is:',my_tuple)
Output
Following is the output of the above code β
The tuple object obtained is: (1, 2, 3)
Example 2
Here, we are using the tuple() function to convert the string "Python" into a tuple of its individual characters β
my_string = "Python"
char_tuple = tuple(my_string)
print('The tuple object obtained is:',char_tuple)
Output
Output of the above code is as follows β
The tuple object obtained is: ('P', 'y', 't', 'h', 'o', 'n')
Example 3
In here, we are using the tuple() function without any arguments, creating an empty tuple (()) β
empty_tuple = tuple()
print('The tuple object obtained is:',empty_tuple)
Output
The result obtained is as shown below β
The tuple object obtained is: ()
Example 4
In this case, we convert the elements of the set "{4, 5, 6}" into a tuple β
my_set = {4, 5, 6}
set_tuple = tuple(my_set)
print('The tuple object obtained is:',set_tuple)
Output
Following is the output of the above code β
The tuple object obtained is: (4, 5, 6)
Example 5
In this example, we use the tuple() function to a nested list "[[1, 2], [3, 4]]", creating a tuple with nested tuples β
nested_list = [[1, 2], [3, 4]]
nested_tuple = tuple(nested_list)
print('The tuple object obtained is:',nested_tuple)
Output
The result produced is as follows β
The tuple object obtained is: ([1, 2], [3, 4])