tuple() Function in Python

Python tuple() Function

In Python, the tuple() function is used to create a tuple object. A tuple is an immutable collection of items, meaning once created, its elements cannot be changed, added, or removed. Tuples are typically used to store related pieces of data together.

The tuple() function can be used in various ways:

Creating an empty tuple:

empty_tuple = tuple()

Creating a tuple from an iterable (e.g., list, string, set, etc.):

my_list = [1, 2, 3]
my_tuple = tuple(my_list)
# Output: (1, 2, 3)

Creating a tuple from a string:

my_string = "hello"
my_tuple = tuple(my_string)
# Output: ('h', 'e', 'l', 'l', 'o')

Creating a tuple with single or multiple items:

single_item_tuple = tuple([42])
multiple_items_tuple = tuple([1, 2, 3, 4, 5])
# Output: (42,)
# Output: (1, 2, 3, 4, 5)

Tuple unpacking with the tuple() function:

a, b, c = tuple([1, 2, 3])
# a = 1, b = 2, c = 3

It's important to note that using tuple() is not necessary to create a tuple directly. You can create a tuple using parentheses without calling the tuple() function:

my_tuple = (1, 2, 3)

Tuples are useful when you want to ensure that the data remains unchanged after creation and when you need an immutable collection. Lists, on the other hand, are mutable, and their elements can be modified, added, or removed.