Skip to main content

1. What is a Tuple?

  • A tuple is an ordered, immutable (unchangeable) collection of elements.
  • Tuples are defined using parentheses () or the tuple() constructor.
  • Tuples can contain elements of different data types.
Example:

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).
Example:

2. Slicing

  • Extract a subtuple using a range of indices.
  • Syntax: tuple[start:stop:step]
Example:

3. Length

  • Use len() to find the number of elements in a tuple.
Example:

4. Concatenation

  • Combine two or more tuples using the + operator.
Example:

5. Repetition

  • Repeat a tuple using the * operator.
Example:

6. Checking for Elements

  • Use the in keyword to check if an element exists in a tuple.
Example:

3. Tuple Methods

1. count()

  • Returns the number of times a specified value occurs in a tuple.
Example:

2. index()

  • Returns the index of the first occurrence of a specified value.
Example:

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.
Example:

5. Unpacking Tuples

  • Assign the elements of a tuple to variables in a single statement.
Example:

6. Nested Tuples

  • A tuple can contain other tuples, creating a multi-level structure.
Example:

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.