In Python, the tuple()
function is a fundamental tool for creating immutable sequences. This article aims to provide a comprehensive guide on its usage, applications, and significance through detailed examples.
Understanding tuple() Function
The tuple()
function in Python is utilized to create immutable sequences, often referred to as tuples. Its syntax is straightforward:
tuple(iterable)
Here, iterable
represents any iterable object, such as lists, strings, or other sequences, from which the tuple is created.
Example 1: Creating a Tuple from a List
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print("Tuple from list:", my_tuple)
Output 1:
Tuple from list: (1, 2, 3, 4, 5)
Example 2: Creating a Tuple from a String
my_string = "hello"
my_tuple = tuple(my_string)
print("Tuple from string:", my_tuple)
Output 2:
Tuple from string: ('h', 'e', 'l', 'l', 'o')
Example 3: Creating an Empty Tuple
empty_tuple = tuple()
print("Empty tuple:", empty_tuple)
Output 3:
Empty tuple: ()
Example 4: Tuple with Mixed Data Types
mixed_data = (1, 'hello', True, 3.14)
print("Tuple with mixed data types:", mixed_data)
Output 4:
Tuple with mixed data types: (1, 'hello', True, 3.14)
Points to Remember
- Tuples are immutable sequences in Python, created using the
tuple()
function. - They are often used to represent fixed collections of items where immutability is desired.
- Tuples can contain elements of different data types and can be nested.