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

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

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

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

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

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])
python-tuple-function.htm
Advertisements