Python list and tuples are the core of python basics. Both are used to store multiple data, but there are some differences between these two (Python List vs Python Tuple). Here we will see the difference between the Python list and the Python tuple.
Differences of Python List and Tuple
Syntax of python list and Python tuple
Python list is created with the square bracket [], whereas Python tuple is created with round brackets ().
Python list example
animals= ["cow", "elephant", "pig"] print(type(animals))
Output
<class 'list'>
Python tuple example
animals= ("cow", "elephant", "pig") print(type(animals))
output
<class 'tuple'>
Immutability
Python lists are mutable in nature means the python list can be changed after its creation, Whereas Python tuples are immutable (cannot be changed once it’s created).
Example: Let’s see by the example
Python list mutable example
animals= ["cow", "elephant", "pig"] animals.insert(3,"Zebra") print(type(animals)) print(animals)
output
<class 'list'> ['cow', 'elephant', 'pig', 'Zebra']
Python tuple immutable example
animals= ("cow", "elephant", "pig") animals[0]="Zebra" print(animals)
Output
TypeError: 'tuple' object does not support item assignment
Explanation: Python tuple will throw error if we try to modify its element or try to add new elements, hence python tuple is immutable in nature.
Point to remember about Python List vs Tuple
- Syntax of Python list and Python tuple is different.
- difference of immutability, Python list is mutable whereas python tuple is immutable.
- Python list is more flexible to use than Python tuple.
- Python list has more functions than Python tuple
- lists are faster than Python tuple.
- Python tuple is fixed length and Python lists are variable length.