Python list and tuples are 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 of Python list and Python tuple.
Page Contents
Differences of Python List and Tuple
Syntax of python list and Python tuple
Python list is created with square bracket [], whereas Python tuple are 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 list are mutable in nature means python list can be change after its creation, Whereas Python tuple are immutable (cannot be change once its created).
Example: Let’s see by 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.
- Tuple are fixed length and Python lists are variable length.
One thought on “Python List vs Python Tuple with example”