List vs Tuple in Python: Key Differences and When to Use Each

 


 

 Summary: What’s the Difference?

Feature List (list) Tuple (tuple)
Mutability  Mutable (can change)  Immutable (cannot change)
Syntax [1, 2, 3] (1, 2, 3)
Performance  Slightly slower  Slightly faster
Use Case Data that changes Fixed data
Methods Available Many (e.g., append()) Few (e.g., count(), index())

 Example: List

fruits = ["apple", "banana", "orange"]
fruits.append("grape")  #  Works!
print(fruits)

 Example: Tuple

colors = ("red", "green", "blue")
# colors.append("yellow")  #  This will raise an AttributeError
print(colors)

 Common Problem

 Error When Trying to Modify a Tuple:

my_tuple = (1, 2, 3)
my_tuple[0] = 100  # TypeError: 'tuple' object does not support item assignment

 Solution:

If you need to modify it, convert it to a list first:

my_tuple = (1, 2, 3)
temp_list = list(my_tuple)
temp_list[0] = 100
my_tuple = tuple(temp_list)
print(my_tuple)  # Output: (100, 2, 3)

When to Use List vs Tuple

  • Use lists when:
    • You need to modify, add, or remove elements
    • You work with dynamic or user-generated data
  • Use tuples when:
    • You need to protect data from being changed
    • You're working with fixed collections (e.g., coordinates, RGB values)
    • You want slightly better performance and memory efficiency

Extra Tip: Tuple Unpacking

point = (10, 20)
x, y = point
print(f"x = {x}, y = {y}")

Conclusion

Both lists and tuples are valuable in Python.

  • If you need flexibility, use a list.
  • If you need safety and speed, use a tuple.

0 Comments:

Post a Comment