DEV Community

Maulik
Maulik

Posted on

Difference Between Python list, tuple, and set

When working with collections of data in Python, three of the most commonly used built-in data structures are list, tuple, and set. Each has unique characteristics and use cases. Understanding their differences is key to writing clean, efficient, and bug-free code.

1. List:

1.1 Characteristics:

  • Mutable (can be modified after creation)
  • Ordered
  • Allows duplicates
  • Elements can be of mixed data types

1.2 Syntax:

my_list = [1, 2, 3, 4, 1] 
Enter fullscreen mode Exit fullscreen mode

1.3 Common Use Cases:

  • When you need to maintain order
  • When the data changes frequently
  • When duplicates are acceptable

2. Tuple:

2.1 Characteristics:

  • Immutable (cannot be modified after creation)
  • Ordered
  • Allows duplicates
  • More memory-efficient than lists

2.2 Syntax:

my_tuple = (1, 2, 3, 4, 1) 
Enter fullscreen mode Exit fullscreen mode

2.3 Common Use Cases:

  • When the data should not be changed
  • When using data as dictionary keys
  • When ensuring data integrity

3. Set:

3.1 Characteristics:

  • Mutable
  • Unordered
  • No duplicate elements
  • Faster for membership tests

3.2 Syntax:

my_set = {1, 2, 3, 4} 
Enter fullscreen mode Exit fullscreen mode

⚠️ my_set = {} creates a dict, not a set. Use set() for an empty set.

3.3 Common Use Cases:

  • When you need unique items
  • For fast membership testing
  • For performing set operations (union, intersection, difference)

4. Quick Comparison Table:

Feature List Tuple Set
Ordered ✅ Yes ✅ Yes ❌ No
Mutable ✅ Yes ❌ No ✅ Yes
Duplicates ✅ Allowed ✅ Allowed ❌ Not allowed
Indexable ✅ Yes ✅ Yes ❌ No
Use in Keys ❌ No ✅ Yes ❌ No
Performance Slower Faster (fixed) Fast (for lookup)

5. Summary:

  • Use a list when you need an ordered, mutable collection with duplicates allowed.
  • Use a tuple for immutable, ordered data — ideal for read-only or fixed data structures.
  • Use a set for unique, unordered data, especially when you need fast membership checks.

6. Real-World Tip:

Choose the right structure for the right job:

  • If you're working with JSON, lists and dictionaries are more natural.
  • If you're designing constants or configurations, tuples are ideal.
  • For deduplication or fast in checks, sets are the way to go.

Top comments (0)