If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, a tuple is a data structure similar to a list, but with one crucial difference: tuples are immutable. Once a tuple is created, you cannot modify its elements or size. Tuples are defined by enclosing a comma-separated sequence of elements within parentheses
( )
.Here's a brief introduction to tuples in Python:
- Creating a Tuple: You can create a tuple by defining it with parentheses and including the elements separated by commas.
Example:
pythonCopy code
# Tuple of integers numbers = (1, 2, 3, 4, 5) # Tuple of strings fruits = ("apple", "banana", "orange") # Mixed data types mixed_tuple = (10, "hello", 3.14, True)
- Accessing Elements: Similar to lists, you can access individual elements in a tuple using their index. The index of the first element is 0, the second element is 1, and so on. Negative indices can also be used to access elements from the end of the tuple.
Example:
pythonCopy code
numbers = (1, 2, 3, 4, 5) print(numbers[0]) # Output: 1 print(numbers[2]) # Output: 3 print(numbers[-1]) # Output: 5 (last element)
- Tuple Packing and Unpacking: You can create a tuple by simply separating values with commas, even without using parentheses. This is known as tuple packing. Additionally, you can unpack a tuple by assigning its elements to multiple variables.
Example:
pythonCopy code
# Tuple packing a = 10 b = "hello" c = 3.14 my_tuple = a, b, c print(my_tuple) # Output: (10, "hello", 3.14) # Tuple unpacking x, y, z = my_tuple print(x) # Output: 10 print(y) # Output: "hello" print(z) # Output: 3.14
- Immutable Nature: Unlike lists, tuples are immutable. Once a tuple is created, you cannot change its elements or size.
Example:
pythonCopy code
numbers = (1, 2, 3, 4, 5) numbers[0] = 10 # This will raise an error since tuples are immutable.
- Uses of Tuples: Tuples are often used to represent collections of related data, where the individual elements have different meanings and cannot be changed after creation. They are commonly used in scenarios where data integrity and immutability are required, such as dictionary keys, function arguments, and returning multiple values from functions.
In summary, tuples are similar to lists but with the key difference that they are immutable. They are used when you need to create a collection of items that should not be modified after creation.
Comments: 0