Python Tuples
Tuples in Python
A tuple is an ordered, immutable (unchangeable) collection of elements. Once a tuple is created, its values cannot be modified (no adding, removing, or changing elements). Tuples are similar to lists but with the key difference being their immutability.
Key Features of Tuples:
- Ordered: Like lists, the elements in a tuple have a defined order.
- Immutable: You cannot change, add, or remove elements once a tuple is created.
- Heterogeneous: Tuples can contain elements of different data types.
- Hashable: Tuples can be used as keys in dictionaries (since they are immutable).
Tuple Syntax:
Tuples are created by enclosing elements in parentheses ()
, with elements separated by commas.
Example: Tuple Creation
Accessing Tuple Elements:
You can access elements in a tuple using an index (starting from 0), just like with lists.
Tuple Immutability:
Once a tuple is created, you cannot modify its elements. If you try to change or remove elements, Python will throw an error.
Tuple Slicing:
You can access a range of elements (slice) in a tuple.
Tuple Operations:
- Concatenation: You can concatenate two or more tuples using the
+
operator.
- Repetition: You can repeat a tuple multiple times using the
*
operator.
- Membership Test: You can check if an element exists in a tuple using the
in
keyword.
Tuple Methods:
Since tuples are immutable, they have fewer built-in methods compared to lists. Two commonly used methods are:
count()
: Returns the number of times a value appears in the tuple.index()
: Returns the index of the first occurrence of a value in the tuple.
Packing and Unpacking Tuples:
Tuple packing refers to the creation of a tuple by directly assigning multiple values. Tuple unpacking allows you to assign the individual elements of a tuple to variables.
Single Element Tuple:
To create a tuple with a single element, you need to include a trailing comma. Without the comma, Python will treat it as a regular value, not a tuple.
Why Use Tuples?
- Immutability: If you don’t want your data to be changed after creation, tuples are a good choice.
- Faster: Tuples can be slightly faster than lists because they are immutable.
- Hashable: Tuples can be used as dictionary keys and in sets, which require hashable objects.
Example: Using Tuples in a Dictionary
Summary:
- Tuples are ordered, immutable collections of elements.
- Once created, the contents of a tuple cannot be changed.
- Tuples are useful when you need to store data that should not be modified.