[TIPS] Python: Compare Tuple and List
By JoeVu, at: 17:06 Ngày 05 tháng 10 năm 2023
In Python, both tuples and lists are used to store collections of items, but they have some key differences. Here's a comparison between tuples and lists:
-
Mutability:
- List: Lists are mutable, which means you can change their contents by adding or removing elements, or by modifying existing elements.
- Tuple: Tuples are immutable, meaning once they are created, their elements cannot be changed, added, or removed.
-
Syntax:
- List: Defined using square brackets
[]
, e.g.,my_list = [1, 2, 3]
. - Tuple: Defined using parentheses
()
, e.g.,my_tuple = (1, 2, 3)
.
- List: Defined using square brackets
-
Performance:
- List: Because of their mutability, lists may require more memory and can have a slightly slower performance compared to tuples.
- Tuple: Tuples are generally more memory-efficient and can offer better performance for certain operations due to their immutability.
-
Use Case:
- List: Use lists when you need a collection that can be modified, such as when you want to add or remove elements dynamically.
- Tuple: Use tuples when you want to create a collection of items that should remain constant throughout the program execution. Tuples are suitable for situations where immutability is desired, like when defining keys for dictionaries.
-
Methods:
- List: Lists have more built-in methods for adding, removing, and manipulating elements, such as
append()
,extend()
,remove()
, andpop()
. - Tuple: Tuples have fewer methods due to their immutability, but they still support common operations like indexing and slicing.
- List: Lists have more built-in methods for adding, removing, and manipulating elements, such as
-
Iteration:
- List: Lists can be iterated using a
for
loop, and elements can be modified during iteration. - Tuple: Tuples can also be iterated, but since they are immutable, their elements cannot be modified during iteration.
- List: Lists can be iterated using a
Here's a quick example:
# List example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
# Tuple example
my_tuple = (1, 2, 3)
# The following line would raise an error since tuples are immutable
# my_tuple.append(4)
In summary, choose between tuples and lists based on whether you need a mutable or immutable collection, and consider performance implications based on the specific requirements of your program.