1. What is a Tuple?
- A tuple is an ordered, immutable (unchangeable) collection of elements.
- Tuples are defined using parentheses
()
or thetuple()
constructor. - Tuples can contain elements of different data types.
2. Tuple Operations
1. Accessing Elements
- Use indexing to access individual elements in a tuple.
- Python uses zero-based indexing (the first element has index
0
).
2. Slicing
- Extract a subtuple using a range of indices.
- Syntax:
tuple[start:stop:step]
3. Length
- Use
len()
to find the number of elements in a tuple.
4. Concatenation
- Combine two or more tuples using the
+
operator.
5. Repetition
- Repeat a tuple using the
*
operator.
6. Checking for Elements
- Use the
in
keyword to check if an element exists in a tuple.
3. Tuple Methods
1. count()
- Returns the number of times a specified value occurs in a tuple.
2. index()
- Returns the index of the first occurrence of a specified value.
4. Immutable Nature of Tuples
- Tuples are immutable, meaning their elements cannot be changed after creation.
- However, if a tuple contains mutable objects (e.g., lists), those objects can be modified.
5. Unpacking Tuples
- Assign the elements of a tuple to variables in a single statement.
6. Nested Tuples
- A tuple can contain other tuples, creating a multi-level structure.
7. Additional Examples
-
Creating a Tuple:
-
Accessing Elements:
-
Slicing:
-
Unpacking:
-
Checking for Elements:
8. Best Practices
- Use tuples for collections of items that should not change (e.g., constants, configurations).
- Use parentheses for clarity, even when defining a single-element tuple (e.g.,
(1,)
). - Prefer tuples over lists for immutable data to ensure data integrity.