Differences between list and tuple in Python
Tuples are used in Python to store elements just like lists. The list is used when you know that you will have to change the elements of the list as you move forward in your program whereas tuples do not allow you to change its elements.
Representation of list and tuple
The list is used for storing elements and is represented by square brackets whereas tuples are represented by using parenthesis.
test_list = ['a', 'b' , 'c'] test_tuple = ('a', 'b', 'c')
Properties of list and tuple in Python
- Lists are mutable, which means the data inside the list can be changed at any point in the program whereas tuple does not allow you to modify the data that it contains.
- Because of mutability, its easier to insert or delete data in lists as compared to tuples which do not allow to insert/delete elements at all.
- Tuples use less memory as they are fixed-sized and are stored in a single block of memory whereas memory is provided to list in smaller blocks which eventually ends up taking a lot of memory as compared to the tuple.
- Elements can’t be replaced in a tuple whereas you can replace an element in a list easily.
- Operations on the tuple can be performed faster as compared to that of the list.
Accessing Elements from list and tuple
Elements in a tuple can be accessed the same way we access the elements in the Python list. For example:-
test_tuple = (10,20) print(test_tuple) print(test_tuple)
Output for the above code will be:
Accessing elements in the Tuple is the same as in Python list. The major difference between these two is that the tuples are immutable while the lists are mutable and operations on the tuples can be performed faster as compared to the list because tuples are stored in a single block of memory and take less space as compared to list in Python.