Difference between Tuple and List in Python | Tuples vs Lists

You should have heard of tuples and lists in Python. If yes, then you also know that these two data structures are similar to each other.

Confused about what is the difference between them and where to use which one of them? This article clears all these doubts. We will cover the differences between tuples and lists, which also include the use cases.

So, let’s first begin with the recap!

Lists in Python

Lists are the collection of heterogeneous values stored in a contiguous memory location. These are mutable, ordered, and allow duplicate values.

1. Declaration of lists in Python

A list is used square brackets to enclose its elements and comma to separate each of them. For example,

list1=[] #empty list
print(f"The type of the {list1} is {type(list1)}")

list2=[1,'PythonGeeks', 3.4,"a",(1,3),['r','u']]
print(f"The type of the {list2} is {type(list2)}")

Output:

The type of the [] is <class ‘list’>

The type of the [1, ‘PythonGeeks’, 3.4, ‘a’, (1, 3), [‘r’, ‘u’]] is <class ‘list’>

2. Accessing Python List Elements

We can access the list by using the list name of the list. We can access any element or a set of elements using indexing. Remember that the index starts with 0! For example,

list1=[3,'t',6.9,'Python',4.0,5]

list1

list1[3]

list1[2:5]

list1[:-2]

Output:

[3, ‘t’, 6.9, ‘Python’, 4.0, 5]

‘Python’

[6.9, ‘Python’, 4.0]

[3, ‘t’, 6.9, ‘Python’]

3. Reassigning and Deleting values of Lists in Python

We can reassign a value using the indexing again. The syntax is

list_name[index]=new_value

And to delete the value we can use the del function and the index of the value we want to delete. The syntax is

del list_name[index]

Example of modifying and deleting elements:

list1=[2,3.8,'a',0.7,'5']

list1[3]=12
list1

del list1[0]
list1

Output:

[2, 3.8, ‘a’, 12, ‘5’]

[3.8, ‘a’, 12, ‘5’]

Tuples in Python

Tuples are also the collection of values of different data types. These are ordered, immutable, and allow duplicate values.

1. Declaration of Python tuples

The elements of a tuple are enclosed by circular brackets and separated by comma. For example,

tup1=() # empty tuple
print(f"The type of the {tup1} is {type(tup1)}")

tup2=(3.5,'y',9,[1,5],('u','o'))
print(f"The type of the {tup2} is {type(tup2)}")

Output:

The type of the () is <class ‘tuple’>

The type of the (3.5, ‘y’, 9, [1, 5], (‘u’, ‘o’)) is <class ‘tuple’>

2. Accessing Python Elements

We can access the entire tuple by using just the name of the tuple. And to access an element or a set of numbers we use indexing. Even here the index starts with 0! Examples of accessing the tuple elements are shown below.

tup=(1,2,'r',[3,4],5.6)

tup

tup[4]

tup[-4:-2]

tup[3:]

Output:

(1, 2, ‘r’, [3, 4], 5.6)

5.6

(2, ‘r’)

([3, 4], 5.6)

3. Reassigning and Deleting values of Python Tuples

Since tuples are immutable, we can neither reassign nor delete the values of a tuple. If we try doing so we get an error as shown below.

tup=(1,2,3,4,5)

tup[4]=4

del tup[2]

Output:

Traceback (most recent call last):
File “<pyshell#29>”, line 1, in <module>
tup[4]=4
TypeError: ‘tuple’ object does not support item assignment
Traceback (most recent call last):
File “<pyshell#30>”, line 1, in <module>
del tup[2]
TypeError: ‘tuple’ object doesn’t support item deletion

Similarities between Python Lists and Tuples

Revisiting the concepts of tuples and lists, let us first discuss some similarities between these two data structures. The similarities are as following:

1. List and tuple, both of them are sequence type data types storing multiple values.

2. Both of them can hold the values of different data types.

3. The elements of both the lists and tuple can be accessed using the index.

4. Both of them can be nested, that is, we can have lists in lists and tuples in tuples. And we can access the elements of them multiple indexing as shown below.

Example of nested lists and tuples:

list1=[[1,2,3],[4,5,6],[7,8,9]]
list1[2][0]

tup=(('j','y','o'),(3,7,2),('y','u','e'))
tup[1][2]

Output:

7

2

Now let us concentrate on the differences between the Python Lists and Tuples.

1. Difference in Syntax

The lists enclose their elements by the square brackets whereas the elements of the tuples are surrounded by the circular brackets.

Example of showing the difference in the syntax of a list and a tuple:

list1=['a','e','i','o','u'] #list

tup=('a','e','i','o','u') #tuple

2. Size

In Python, tuples occupy a lesser amount of size compared to the lists. Dice tuples are immutable, larger blocks of memory with lower overhead are allocated for them. Whereas as for the lists, small memory blocks are allocated. This property also makes tuples faster than the lists, when they have large numbers of elements.

The below example shows the size of each of the tuples and the list with the same elements.

list1=['a','e','i','o','u']
print(f"Size of list is {list1.__sizeof__()}")

tup1=('a','e','i','o','u')
print(f"Size of tuple is {tup1.__sizeof__()}")

Output:

Size of list is 104

Size of tuple is 64

It can be seen that for the same elements, the size of a list is larger than that of a tuple.

3. Mutability

This is one of the important differences between the lists and the tuples. Mutability is the property of an element to be modified. In Python, lists are mutable whereas tuples are not.

We can reassign or delete the values of lists but when we try doing the same thing with the tuples we get an error. These results are shown below.

list1=[1,2,3,4,5]

list1[4]=6
list1

del list1[3]
list1

Output:

[1, 2, 3, 4, 6]

[1, 2, 3, 6]

Example on immutability of a tuple:

tup=('a','b','c','d','e')
tup[3]='t'

del tup[1]

Output:

Traceback (most recent call last):
File “<pyshell#48>”, line 1, in <module>
tup[3]=’t’
TypeError: ‘tuple’ object does not support item assignment
Traceback (most recent call last):
File “<pyshell#49>”, line 1, in <module>
del tup[1]
TypeError: ‘tuple’ object doesn’t support item deletion

4. Functions and Methods

There are many functions, and methods that are common to both the lists and the tuple. These are len(), max(), min(), sorted(), sum() all(), any(), index(), and count().

These are the functions that do not modify the constructs. Many other built-in methods are not common. These are the functions that modify the constructs like append(), del, etc. The built-in methods and functions of each of the list and tuple can be found out by the dir() command as shown below.

dir(list)

Output:

[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__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’]

Example of finding the built-in methods and functions of tuples:

dir(tuple)

Output:

[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__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’]

5. Tuples in Lists and Lists in Tuples

We can use tuples as elements of the lists and vice versa. This is done to increase the readability of the values. The following example shows how to do so.

tup=([1,2,3],['a','b','c'],[3.4,5.7,2.0])
type(tup)

list1=[(4.5,6),(12,9,5),('t','g','l')]
type(list1)

Output:

<class ‘tuple’>

<class ‘list’>

6. Length

The length of a tuple is fix whereas the length of a list is variable. The reason again is the immutability property.

7. Debugging

Tuples are generally preferred for large projects where we know the information need not be changed. This is because tuples are mutable and hence it is easier to track them. This makes them programmer-friendly when it comes to debugging as compared to the lists. For smaller projects, you can use lists.

8. Usage

Lists are useful to store a list of homogeneous items. And tuples are used where we store heterogeneous values like details of a person/user. There is no restriction on this, but this is just a general habit followed.

Lists are used in cases where we need to change or delete the values. Whereas the tuples are used in cases where we give read-only property.

And another prominent place where tuples come of use but not the lists is the keys of a dictionary. Remember a dictionary is a data structure with key-value pairs. In a dictionary, the keys are unique and immutable. Because of this immutable property of the keys, we can use tuples. But when we try using a list as a key, we get an error.

The below example shows this.

dic1={(1,2,3):'a',(4,5,6):'b',(8,9,0):'c'}
dic1

dic2={[1,2,3]:'a',[4,5,6]:'b',[8,9,0]:'c'}

Output:

{(1, 2, 3): ‘a’, (4, 5, 6): ‘b’, (8, 9, 0): ‘c’}

Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
dic2={[1,2,3]:’a’,[4,5,6]:’b’,[8,9,0]:’c’}
TypeError: unhashable type: ‘list’

Python Lists vs Tuples

Done with a comparison of lists and tuples in Python, the following table summarizes the differences between them.

Tuples Lists
In tuples, the elements are enclosed by circular brackets. The elements of a list are enclosed by square brackets.
The tuples are immutable Lists are mutable
They occupy less memory and the operations are faster compared to the lists. Compared to the tuples, the lists occupy more memory and are slower.
Used where we need retrieval of data and have read-only mode. Used where operations like insertion and deletion occur frequently.
Only index and count ate the built-in methods that can be applied. Many built-in methods are available to apply.
The occurrence of unexpected changes and errors is less  There is a higher chance of occurrence of unexpected errors and changes compared to the tuples.

Interview Questions on Difference Between Python Lists and Tuples

Q1. Write a program to use lists as keys in a dictionary.
Ans. We can convert the list into a tuple and use it as a key as shown below:

list1=['a','b','c']
list2=[5,0,2]
list3=[4.5,0.2,1.9]

dic1={tuple(list1):'strings',tuple(list2):'integers',tuple(list3):'floats'}
dic1

Output:

{(‘a’, ‘b’, ‘c’): ‘strings’, (5, 0, 2): ‘integers’, (4.5, 0.2, 1.9): ‘floats’}

Q2. Write a program to delete a value from a tuple without getting an error.
Ans. We can convert the tuple into a list, delete the value and convert it back to a tuple as below:

tup=(1,2,3,4,5,6)

list1=list(tup)
del list1[4]

tup=tuple(list1)
tup

Output:

(1, 2, 3, 4, 6)

Q3. Create a list with tuples as its elements and access an element of an inner tuple.
Ans. Below is the example of lists with inner elements as tuples:

list1=[(1,2),(3,5,7),(0,9)]

list1[2][1]

list1[1][0]

Output:

9

3

Q4. Write a program to find the maximum value of a list and a tuple.
Ans. We can use the max() function on both the tuple and the list as below:

list1=[-5,2,0.9,4,-3]
max(list1)

tup=(3,2,1.6,-4.5,9.0)
max(tup)

Output:

4

9.0

Q5. Write a program to add an element to a tuple without any data conversion.

Ans. We can use the ‘+’ operation to add a tuple with a single value to the existing tuple. Since here we change the entire tuple and do not modify any elements, we do not get any error.

tup=(5,'r',9.5,'y')
tup1=(4,)

tup=tup+tup1
tup

Output

(5, ‘r’, 9.5, ‘y’, 4)

Quiz on Difference between tuple and list in Python

Conclusion

In this article, we have first recapped the tuples and lists. Then we saw similarities and Differences between tuple and list in Python. We also saw the uses of each of them in different situations.

Hoping that you understood the sub-topics covered. Happy learning.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *