🐍 Python Q103 / 170

What is the difference between a Python list and a tuple?

AI-Powered Answer ✓ Answered

In Python, both lists and tuples are fundamental data structures used to store collections of items. While they share similarities such as being ordered and capable of holding heterogeneous data types, their primary distinction lies in their mutability, which dictates whether they can be modified after creation.

Key Differences: Mutability

The most significant difference between Python lists and tuples is their mutability. Mutability refers to whether an object's state can be changed after it has been created.

Lists (Mutable)

Lists are mutable, ordered collections of items. This means that after a list is created, you can add, remove, or modify elements within it. Lists are defined using square brackets [].

Tuples (Immutable)

Tuples are immutable, ordered collections of items. Once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined using parentheses ().

Comparative Overview

FeatureListTuple
MutabilityMutable (changeable)Immutable (unchangeable)
SyntaxSquare brackets `[]`Parentheses `()`
MethodsMany (append, extend, insert, remove, sort, pop, etc.)Fewer (count, index)
PerformanceSlightly slower for iteration/access (due to mutability overhead)Slightly faster for iteration/access (fixed size), can be used as dictionary keys (hashable)
Use CasesCollections that need to change (e.g., shopping cart items, dynamic data sets)Fixed collections of related items (e.g., coordinates, database records, function return values, configuration settings)
Memory UsageGenerally uses more memory due to overhead for dynamic resizingGenerally uses less memory as size is fixed

Practical Examples

List Example: Demonstrating Mutability

python
my_list = [10, 20, 30]
print(f"Original list: {my_list}")

# Add an element
my_list.append(40)
print(f"After appending: {my_list}")

# Change an element
my_list[0] = 5
print(f"After changing element at index 0: {my_list}")

# Remove an element
my_list.remove(20)
print(f"After removing 20: {my_list}")

Tuple Example: Demonstrating Immutability

python
my_tuple = (100, 200, 300)
print(f"Original tuple: {my_tuple}")

# Attempting to add an element will raise an AttributeError
# my_tuple.append(400) # This line would cause an error: AttributeError: 'tuple' object has no attribute 'append'

# Attempting to change an element will raise a TypeError
# my_tuple[0] = 50 # This line would cause an error: TypeError: 'tuple' object does not support item assignment

print("Tuple elements cannot be changed after creation.")
print(f"Tuple remains unchanged: {my_tuple}")

# However, you can reassign the variable to a new tuple (creating a new tuple object)
my_tuple = (1, 2, 3)
print(f"After reassigning the variable to a new tuple: {my_tuple}")

In summary, choose a list when you need a collection whose contents can be modified (e.g., adding, removing, or changing items). Choose a tuple when you need a fixed collection of items that should not change after creation, or when you need a hashable collection (e.g., for dictionary keys or set elements). This fundamental difference in mutability significantly impacts their usage, performance characteristics, and the types of operations you can perform.