DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python FundamentalsTopic 42 of 77
←PreviousPrevNextNext→

Tuple Methods

Core Methods Deep Dive

Tuples have two built-in methods with important behaviors:

- **count()**: Returns number of occurrences of a value

- **index()**: Finds first position of a value

- **Special Methods**: Implement sequence protocol (__getitem__, __len__, etc.)

- **No Mutating Methods**: Unlike lists, tuples lack append(), remove(), etc.

Example
t = (1, 2, 2, 3, 4, 2, 5)

# count() method
print(t.count(2))  # 3
print(t.count(9))  # 0

# index() method
print(t.index(3))        # 3
print(t.index(2, 2))     # 2 (start searching at index 2)
print(t.index(2, 3, 6))  # 5 (search between indices 3 and 6)

try:
    t.index(9)
except ValueError as e:
    print(f"Error: {e}")
Output
3
0
3
2
5
Error: tuple.index(x): x not in tuple

Special Method Implementations

Tuples implement several special methods that enable their behavior:

- **Sequence Protocol**: __len__, __getitem__, __contains__

- **Comparison**: __eq__, __lt__, etc. for lexicographical ordering

- **Hashing**: __hash__ for use as dictionary keys

- **Iteration**: __iter__ for for-loops and comprehensions

Example
# Demonstrate special methods
t = (1, 2, 3)

# __len__
print(len(t))  # 3

# __getitem__
print(t[1])    # 2
print(t[1:3])  # (2, 3)

# __contains__
print(2 in t)  # True

# __hash__
d = {t: "value"}  # Works because tuples are hashable
print(d[t])

# __iter__
for item in t:
    print(item)
Output
3
2
(2, 3)
True
value
1
2
3

Performance Characteristics

Tuple method performance considerations:

- **count()**: O(n) time - must scan entire tuple

- **index()**: O(n) time in worst case

- **in Operator**: O(n) average case (uses __contains__)

- **Hashing**: O(n) for first hash, then O(1) (hash is cached)

Example
from timeit import timeit

setup = "t = tuple(range(1000000))"

print("count(999999):", timeit("t.count(999999)", setup=setup, number=10))
print("index(999999):", timeit("t.index(999999)", setup=setup, number=10))
print("999999 in t:", timeit("999999 in t", setup=setup, number=10))
print("hash(t):", timeit("hash(t)", setup=setup, number=1))
ℹ️ Note: For frequent lookups, consider converting to a set or dictionary for O(1) average-time membership tests.

Real-world Method Patterns

Use CaseMethod PatternExample
Data Validationcount()if t.count(None) > threshold
Position Findingindex()idx = headers.index('Date')
Configurationin operatorif 'debug' in settings
Memoizationhash()@lru_cache(maxsize=None)
Sequence Protocol__getitem__for x in sequence
Test your knowledge: Tuple Methods
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python FundamentalsTopic 42 of 77
←PreviousPrevNextNext→