Python Tuples
Python tuples are ordered, immutable collections of objects. They are similar to lists in Python but have a few key differences. Here are some important characteristics of tuples:
- Immutable: Tuples are immutable, which means their elements cannot be modified after creation. Once a tuple is created, you cannot change, add, or remove individual elements. However, you can create a new tuple by concatenating or slicing existing tuples.
- Ordered: Tuples maintain the order of elements. The position of an item in a tuple can be used to access it later. This distinguishes tuples from sets, which are unordered collections.
- Heterogeneous elements: Tuples can contain elements of different data types, such as numbers, strings, lists, and even other tuples.
- Indexed and sliced: You can access individual elements in a tuple using their index. Tuple indices start at 0 for the first element. Additionally, you can use slicing to extract a subset of elements from a tuple.
Here’s an example of creating and working with tuples in Python:
python
# Creating a tuple
my_tuple = (1, 2, "three", [4, 5])
# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: three
# Slicing
print(my_tuple[1:3]) # Output: (2, "three")
print(my_tuple[:2]) # Output: (1, 2)
print(my_tuple[2:]) # Output: ("three", [4, 5])
# Concatenating tuples
another_tuple = (6, 7)
combined_tuple = my_tuple + another_tuple
print(combined_tuple) # Output: (1, 2, "three", [4, 5], 6, 7)
Tuples are commonly used to represent collections of related values when immutability is desired, such as coordinates, database records, or pairs of values.