What is the difference between lists and tuples in Python?
Python's lists and tuples may seem pretty similar in syntax and function, however they have some major differences the most important of which is the fact that lists are mutable and tuples aren't. Here's a quick breakdown:
[1, 2, 3]
- Contained elements are mutable (can be changed after creation)
- Lists have a variable length
- A list takes up more memory than a tuple
(1, 2, 3)
- Contained elements are immutable (cannot be changed after creation)
- Tuples have a fixed length
- A tuple takes up less memory than a list
When to use each one
Lists provide a more accessible API and should be used whenever similar types of objects need to be stored and are expected to change over the course of the application's execution. On the other hand, tuples should be used for immutable data, behaving more like constants than variables.
Learn the difference between two common ways to access values in Python dictionaries and level up your code today.
Learn the difference between Python’s built-in list sorting methods and when one is preferred over the other.
Understand Python's named tuples and start using them in your projects today.