In Python, a tuple is an immutable sequence, meaning that once it’s created, you can’t modify it (no adding, removing, or changing elements). Tuples often store multiple items in a single variable, especially when the data should remain constant throughout the program. Here’s a breakdown of key points about tuples:
Creating a Tuple with Multiple Elements
Tuples are created by placing values inside parentheses ()
separated by commas:
tupleData = (1, 2, 3, 4, 5)
Creating a Tuple Without Parentheses (Tuple Packing)
You can also create a tuple by simply listing values separated by commas without parentheses (this is called tuple packing):
tupleData = 1, 2, 3, 4, 5
Creating an Empty Tuple
An empty tuple can be created by using empty parentheses:
empty_tuple = ()
Creating a Tuple with a Single Element
To create a tuple with a single item, you need to add a comma after the element. Without the comma, Python treats it as a single value in parentheses:
single_item_tuple = (6,) # This is a tuple with one element
not_a_tuple = (6) # This is just an integer, not a tuple
Using the tuple()
Constructor
You can create a tuple from other iterable types (like lists or strings) by using the tuple()
constructor:
# From a list
my_list = [1, 2, 3, 4, 5]
tuple_from_list = tuple(my_list)
# From a string
string = "hello"
tuple_from_string = tuple(string)