Learn Python – Python List Vs Tuple- Basic and advance

In this tutorial, we will analyze the essential distinction between the list and tuples and how each are enjoying a widespread role in Python.

Lists and Tuples are used to keep one or greater Python objects or data-types sequentially. Both can shop any information such as integer, float, string, and dictionary. Lists and Tuples are comparable in most elements however right here we will describe the important distinction between them.

Let’s discuss the predominant variations in the following points.

Representation Differences

The illustration of the Lists and tuple is marginally different. List are in many instances enclosed with the square bracket [], and elements are comma-separated element. Tuples are enclosed with parenthesis (), and elements are separated by using the comma. The parenthesis is optionally available to use, and these kinds of tuples are referred to as tuple packing.

Consider the following example.

list1 = ['JavaTpoint', 1, 2, 54.30, {'Name: ''Peter'}]  
print(type(list))  
tuple1 = ('JavaTpoint',5,8,31.9,[1,2,3])  
print(type(tuple1))  

Output:

<class 'list'>
<class 'tuple'>

In the above program, we described a list1 variable which holds a list of exclusive data type from index 0 to four We defined any other variable tuple1, which holds a tuple of special statistics types. It is enclosed through the ().

Mutable Lists and Immutable Tuples

It is the most essential distinction between list and tuple whereas lists are mutable, and tuples are immutable. The lists are mutable which potential the Python object can be modified after creation, whereas tuples can’t be modified after creation. Consider the given an example.

a = ["Peter","Joseph","Mathew","Ricky"]  
print(a)  

Output:

['Peter', 'Joseph', 'Mathew', 'Ricky']

Now we are altering 0th index thing “Peter” to “Samson”.

a[0] = "Samson"  
print(a)  

Output:

['Samson', 'Joseph', 'Mathew', 'Ricky']

Now we create a tuple and do the same thing.

a = (10,20,"JavaTpoint",30,40)  
print(a)  

Output:

(10, 20, 'JavaTpoint', 30, 40)
a[0] = 50  

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-52b2981fae12> in <module>
----> 1 a[0] = 50

TypeError: 'tuple' object does not support item assignment

We get an error whilst altering the 1st aspect of the tuple because of immutability. It does now not help item assignment.

Debugging

The tuples are effortless to debug in a large venture due to the fact of its immutability. If we have a small mission or less wide variety of data, then lists play an positive role. Let’s reflect onconsideration on the following example:

a = [6,9,4,3,7,0,1]  
# Copying address of a in b  
b = a  
a[3] = "JavaToint"  
print(a)  

Output:

[6, 9, 4, 'JavaToint', 7, 0, 1]

In the above code, we did b = a; right here we are now not copying the listing object from b to a. The b referred to the address of the listing a. It skill if we make the alternate in the b then that will reflect the equal as in list a, and it makes debugging easy. But it is difficult for the considerable project where Python objects may additionally have more than one references.

It will be very complex to track these modifications in lists however immutable object tuple cannot change after created.

So tuples are easy to debug.

Functions Support

The tuples support much less operation than the list. The built in dir(object) is used to get all the supported functions for the listing and tuple.

List Functions

dir(list)  

Output:

['__add__','__class__','__contains__','__delattr__','__delitem__','__dir_,
 '__doc__','__eq__','__format__', '__get__','__getattribute__','__getitem_' '__gt__','__hash__','__iadd__','__imul__','__init__','__init_subclass__''__iter__','__le__','__len__','__lt__','__mul__', '__ne__','__new__',
 '__reduce__', '__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__sizeof__','__str__','__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

Tuple Functions

dir(tuple)  

Output:

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

Memory Efficient

The tuples are extra memory environment friendly than the listing because tuple has less built-in operations. Lists are appropriate for the fewer factors whereas tuples are a bit quicker than the listing for the massive amount of data.

Tuple = (1,2,3,4,5,6,7,8,9,0,5485,87525,955,3343,53234,6423,623456,234535)  
List = [1,2,3,4,5,6,7,8,9,0,78,34,43,32,43,55,54,212,642,533,43434,54532 ]  
print('Tuple size =', Tuple.__sizeof__())       # Tuple size = 52  
print('List size =', List.__sizeof__())    

Output:

Tuple size = 168
List size = 216

Conclusion

In Some cases, lists might seem more useful than tuples. But tuples are important data structures of the Python. Tuples are commonly used for unchangeable data or we can say that the data will be “write- protected” in the tuples. Tuples sends the indication to the Python interpreter the data should not change in the future.

We can use tuple the same as a dictionary without using keys to store the data. For example-

list1 = [(101, "Mike", 24),(102, 'Hussey', 26),(103, 'David', 27),(104,  'Warner', 29)]  

Tuples can use for the dictionary keys because these are hashable and immutable whereas lists can’t use a keys in dictionary.

dict = {("Mike",22):24000}    #valid dictionary  
dict = {["Peter",26]:25000}   #Invalid dictionary