Tuesday, 8 July 2025

Comparison Table: List vs Tuple vs Set

Comparison Table: List vs Tuple vs Set

Feature List Tuple Set
Definition Ordered, mutable collection Ordered, immutable collection Unordered, mutable collection
Syntax [1, 2, 3] (1, 2, 3) {1, 2, 3} or set()
Order maintained? ✅ Yes ✅ Yes ❌ No
Indexing supported? ✅ Yes (e.g., list[0]) ✅ Yes (e.g., tuple[0]) ❌ No
Mutable (changeable)? ✅ Yes ❌ No ✅ Yes (but only items, not by index)
Allow duplicate values? ✅ Yes ✅ Yes ❌ No
Allow different data types? ✅ Yes ✅ Yes ✅ Yes
Used for General-purpose collection Fixed data that shouldn't change Mathematical operations, unique items
Methods available Many (append, pop, sort, etc.) Few (count, index) Set operations (union, intersection)
Performance Slower for membership tests Fast for fixed-size data Fastest for membership testing
Hashable? ❌ No ✅ Yes (if all items are hashable) ❌ No
Common use case Storing items in order Storing constant data Removing duplicates, fast lookup

🔸 Example

# List
my_list = [1, 2, 3, 4, 4]

# Tuple
my_tuple = (1, 2, 3, 4)

# Set
my_set = {1, 2, 3, 4, 4}  # Output: {1, 2, 3, 4}

Key Takeaways

  • Lists are your go-to for ordered, mutable collections that need frequent modifications
  • Tuples are perfect for fixed data that shouldn't change (like coordinates or database records)
  • Sets excel at membership testing, removing duplicates, and mathematical operations
  • Choose the right data structure based on your needs for mutability, ordering, and uniqueness

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...