A tuple is an ordered, immutable sequence of elements in Python. It is similar to a list, but unlike lists, tuples cannot be modified once created. Tuples are defined by enclosing the elements in parentheses, separated by commas. The elements can be of different data types, such as integers, strings, floats, or even other tuples.
To create a tuple in Python, you can simply enclose the elements in parentheses:
my_tuple = (1, 2, "Hello", 3.14)
In the example above, we have created a tuple named my_tuple
containing four elements: an integer, another integer, a string, and a float. Note that the elements are separated by commas.
You can access individual elements of a tuple using indexing. The index starts from zero for the first element and increments by one for each subsequent element. For example, to access the second element of my_tuple
, you can use my_tuple[1]
:
print(my_tuple[1])
This will output:
2
As mentioned earlier, tuples are immutable, which means you cannot modify them once created. If you try to assign a new value to an element of a tuple, Python will raise an error. For example:
my_tuple[0] = 10
This will result in a TypeError
with the message "tuple object does not support item assignment".
Although tuples are immutable, you can perform various operations on them, such as concatenation, repetition, and slicing.
You can concatenate two tuples using the +
operator:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
In this example, concatenated_tuple
will be (1, 2, 3, 4, 5, 6)
.
You can repeat a tuple multiple times using the *
operator:
tuple1 = (1, 2, 3)
repeated_tuple = tuple1 * 3
In this example, repeated_tuple
will be (1, 2, 3, 1, 2, 3, 1, 2, 3)
.
You can extract a portion of a tuple using slicing. Slicing allows you to specify a range of indices to extract. For example:
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
In this example, sliced_tuple
will be (2, 3, 4)
. Note that the start index is inclusive, while the end index is exclusive.
In summary, a tuple in Python is an ordered, immutable sequence of elements. Tuples are created using parentheses and can contain elements of different data types. Although tuples cannot be modified once created, you can perform various operations on them, such as concatenation, repetition, and slicing.