Python | Difference Between List and Tuple
List and Tuple in Python are the class of Python Data Structure. The list is dynamic, whereas the tuple has static characteristics.
What is a List in Python?
The List is just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. In Python, the list is a type of container in Python Data Structures, which is used to store multiple data at the same time. Lists are a useful tool for preserving a sequence of data and further iterating over it.
Syntax of List
list_data = ['an', 'example', 'of', 'a', 'list']
What is a Tuple in Python?
A Tuple is also a sequence data type that can contain elements of different data types, but these are immutable in nature. In other words, a tuple is a collection of Python objects separated by commas. The tuple is faster than the list because of static in nature.
Syntax of Tuple
tuple_data = ('this', 'is', 'an', 'example', 'of', 'tuple')
Difference Between List and Tuple in Python
SR.NO. | LIST | TUPLE |
---|---|---|
1 | Lists are mutable | Tuples are immutable |
2 | The implication of iterations is Time-consuming | The implication of iterations is comparatively Faster |
3 | The list is better for performing operations, such as insertion and deletion. | Tuple data type is appropriate for accessing the elements |
4 | Lists consume more memory | Tuple consumes less memory as compared to the list |
5 | Lists have several built-in methods | Tuple does not have many built-in methods. |
6 | The unexpected changes and errors are more likely to occur | In tuple, it is hard to take place. |
List vs Tuple
Tuples are immutable, whereas lists are mutable, and this is the main distinction between the two. Why does this matter? The values in a list can be changed or modified, while the values of a tuple cannot.
Python3
# Creating a List with # the use of Numbers # code to test that tuples are mutable List = [ 1 , 2 , 4 , 4 , 3 , 3 , 3 , 6 , 5 ] print ( "Original list " , List ) List [ 3 ] = 77 print ( "Example to show mutablity " , List ) |
Output:
Original list [1, 2, 4, 4, 3, 3, 3, 6, 5] Example to show mutablity [1, 2, 4, 77, 3, 3, 3, 6, 5]
Code to test that tuples are immutable
Python3
#code to test that tuples are immutable tuple1 = ( 0 , 1 , 2 , 3 ) tuple1[ 0 ] = 4 print (tuple1) |
Output:
Traceback (most recent call last): File "e0eaddff843a8695575daec34506f126.py", line 3, in tuple1[0]=4 TypeError: 'tuple' object does not support item assignment