List & Tuple

What is the difference between a list and a tuple?

If your first answer was Lists are mutable and Tuples are immutable - well you’re right. But can you explain them?
If yes, then great. Else, you might want to go through this page.

Let’s take a list and a tuple

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

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

now let’s add perform some actions on these datatypes.

lets replace the first element in the list

myList = [1,2,3,4,5]
myTuple = (1,2,3,4,5)

myList[0] = 10

print(myList)

"""
OUTPUT
[10, 2, 3, 4, 5]
"""

well, we’re able to do that since it is mutable.

now let’s do the same thing with the list.

myList = [1,2,3,4,5]
myTuple = (1,2,3,4,5)

myTuple[0] = 10

print(myTuple)

"""
ERROR!
Traceback (most recent call last):
  File "<main.py>", line 11, in <module>
TypeError: 'tuple' object does not support item assignment
"""

We get an error because a tuple once defined, cannot be altered.

Similarly any operation you do with a list (like append, pop) will result in the same error when you try to do it to a tuple.

This is pretty basic, so ensure you’re solid on this.

Updated on