Python Tuple vs List

Differences Between tuple and list in Python

Both tuples and lists are used to store collections of items, but they have key differences in mutability, performance, and usage.


1️⃣ Key Differences

Featuretuplelist
Mutable?❌ No (Immutable)✅ Yes (Mutable)
Performance✅ Faster (Uses less memory)❌ Slower (More memory overhead)
Methods Available❌ Limited (count(), index())✅ Many (append(), pop(), remove(), etc.)
Uses Parentheses () or Brackets []?(1, 2, 3)[1, 2, 3]
Can Be Used as a Dictionary Key?✅ Yes (Hashable)❌ No (Not Hashable)
Best Used For?Fixed collections (coordinates, database records)Dynamic collections (lists of items)

2️⃣ tuple (Immutable & Faster)

A tuple is an immutable ordered collection.

# Creating a tuple
t = (1, 2, 3)
print(t[0])  # Output: 1

# t[0] = 5  # ❌ ERROR: Tuple is immutable

Use tuples when data should not change (e.g., (latitude, longitude), configuration settings).
Tuples are hashable, meaning they can be used as dictionary keys.

locations = {(40.7128, -74.0060): "New York"}
print(locations[(40.7128, -74.0060)])  # Output: New York

3️⃣ list (Mutable & Dynamic)

A list is a mutable ordered collection.

# Creating a list
lst = [1, 2, 3]
lst.append(4)  # ✅ Allowed: Lists are mutable
print(lst)  # Output: [1, 2, 3, 4]

lst[0] = 5  
print(lst)  # Output: [5, 2, 3, 4]

Use lists when the data needs to change dynamically.
Supports sorting, removing, and modifying elements.


4️⃣ Performance Comparison

Tuples are faster and use less memory because they are immutable.

import sys
lst = [1, 2, 3, 4, 5]
tup = (1, 2, 3, 4, 5)

print(sys.getsizeof(lst))  # More memory
print(sys.getsizeof(tup))  # Less memory

Use tuples for better memory efficiency when data doesn’t change.


5️⃣ When to Use Which?

Use tuples for fixed data, and lists for dynamic data!

Use CaseChoose tuple or list?
Data never changestuple
Data needs modificationlist
Dictionary keytuple
Fast iteration & memory efficiencytuple
Need append, remove, or sortinglist

發佈留言