Python Lists vs Tuples
In Python, both lists and tuples are used to store multiple items in a single variable. However, they have some key differences in terms of mutability, syntax, and usage. Let's explore these differences in detail.
Definition
- Lists: A list is a collection of items that are ordered, changeable, and allows duplicate elements. Lists are defined using square brackets
[]
. - Tuples: A tuple is a collection of items that are ordered, unchangeable (immutable), and allows duplicate elements. Tuples are defined using parentheses
()
.
Comparison Table: Lists vs Tuples
Feature | Lists | Tuples |
---|---|---|
Syntax | Defined using [] |
Defined using () |
Mutability | Mutable (can be modified) | Immutable (cannot be modified) |
Methods | Supports many built-in methods like append() , remove() , etc. |
Supports only a few methods like count() , index() |
Memory Usage | Consumes more memory | Consumes less memory |
Performance | Slower due to mutability | Faster due to immutability |
Use Case | Best for collections of items that can change | Best for collections of items that should not change |
Example 1: Creating a List
# Example: Creating a List
my_list = [1, 2, 3, 4, 5]
print("List:", my_list)
Output
Example 2: Creating a Tuple
# Example: Creating a Tuple
my_tuple = (1, 2, 3, 4, 5)
print("Tuple:", my_tuple)
Output
Let's see the difference in mutability between lists and tuples. We will try to modify both a list and a tuple.
Example 3: List vs Tuple Mutability
# Example: List vs Tuple Mutability
# Modifying a List
my_list = [10, 20, 30]
my_list[0] = 100
print("Modified List:", my_list)
# Trying to modify a Tuple
my_tuple = (10, 20, 30)
try:
my_tuple[0] = 100
except TypeError as e:
print("Error:", e)
Output
Example 4: List Methods
# Example: Using List Methods
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print("List after append:", fruits)
Output
Example 5: Tuple Methods
# Example: Using Tuple Methods
numbers = (1, 2, 2, 3)
count_of_twos = numbers.count(2)
index_of_three = numbers.index(3)
print("Count of 2:", count_of_twos)
print("Index of 3:", index_of_three)
Output
In summary, lists and tuples in Python are similar in many ways but differ in terms of mutability and performance. Use lists when you need a collection of items that can be modified, while tuples are best suited for collections that should remain unchanged. Understanding the differences between these two data structures will help you write more efficient and readable Python code.