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])
python_type_casting.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy