Python Tuples vs Lists – The clash of Mutables and Immutables

In this Python tuples vs lists article, we are going to see the things that make tuples and lists similar and things that distinguish them from each other.

Tuples and lists have a lot in common so one can easily get confused about what to use when.

We will also learn some good practices and how you can effectively decide which one you should use in different situations.python tuples vs lists

Python Tuples vs Lists

Now, we are going to see different parameters differentiating Python tuples and lists.

Syntax Differences

Let’s start by a quick study of Tuples and lists syntax structures.

Python Tuples

Tuple is a collection of items and they are immutable. To create a tuple, we surround the items in parenthesis ().

Code:

tuple1 = (1,2,3,4)
tuple2 = (1,2.5,”Hey”, False )
print( type(tuple1) )

Output:

<class ‘tuple’>

Python Lists

Lists are a mutable collection of items. We use square brackets to surround the items [].

Code:

list1 = [1,2,3,4]
list2 = [1, 5.5, “Hello”, True]
print( type(list1) )

Output:

<class ‘list’>

Accessing, Indexing, Slicing

In most of the parts, tuples and lists are similar to each other. Indexing and slicing are the same in tuples as lists.

Let’s see a quick example.

Code:

list1 = [1, 2, 4, 5, 8, 9]
tuple1 = (1, 2, 4, 5, 8, 9)
print( list1[3] , tuple1[3] )
print( list1[1:3] , tuple1[1:3] )

Output:

5 5
[2, 4] (2, 4)

Mutability

This is the most important difference that distinguishes tuples from lists.

Mutability means the ability to change. In the context of Python objects, a mutable object can be changed by adding or removing items.

Mutable List

Lists are mutable in nature which means we can add or remove items from the list. Let’s try changing and adding a new element in our list.

Code:

list1 = [1, 2, 4, 4]
list1[2] = 3
print(list1)
list1.append(5)
print(list1)

Output:

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

As you see, we can change and add new elements in the list without any problem. Now let’s try removing the element at the second index from the list.

Code:

list1.remove(2)
print(list1)

Output:

[1, 3, 4, 5]

Hence we see that lists are mutable creatures.

Immutable Tuple

Tuples are immutable so we cannot change, add or remove any item once a tuple is created. Let’s try changing a value in tuple.

Code:

tuple1 = (1, 2, 3, 4)
tuple1[2] = 3

Output:

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
TypeError: ‘tuple’ object does not support item assignment

Tuples items cannot be changed however, we can reassign the entire tuple.

Code:

tuple1 = (10, 30, 20, 40)
print( tuple1 )
tuple1 = (99, 100, 101, 102)
print( tuple1 )

Output:

(10, 30, 20, 40)
(99, 100, 101, 102)

Now the variable is reassigned to reference a different tuple.

Methods

There are differences in the available methods on lists and tuples. Some methods are common in both the data structures.

Other methods like append(), insert(), pop(), remove(), reverse() and sort() are available in lists while tuples have less methods because of its nature of immutability.

Python List Methods

There are 46 available methods on lists.

Code:

len(dir( list))
dir( list )

Output:

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

Python Tuple Methods

There are 33 available methods on tuples.

Code:

len(dir( tuple))
print( dir( tuple ) )

Output:

33
[‘__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’]

Functions

Most of the Python functions can be applied on both lists and tuples. These functions include len(), max(), min(), sum(), any(), all(), sorted().

Let’s see some of those and you can check the rest by applying yourself.

Code:

num_list = [3,8,6,4,10]
num_tuple = (3,8,6,4,10)

print( max(num_list), max(num_tuple) )
print( sum(num_list), sum(num_tuple) )
print( sorted(num_list), sorted(num_tuple) )

Output:

10 10
31 31
[3, 4, 6, 8, 10] [3, 4, 6, 8, 10]

Python Tuples vs Lists – When to Use What?

Now we know the similarities and differences between tuples and lists.

You might be thinking about when should we use tuples and when to use lists.

1. Tuples are used where we don’t need to change, add or remove any element. Using tuples also indicated developers that the value is not meant to change.

2. If you have to update, add or remove an element in a collection then lists should be used.

3. Tuples are faster than lists when iterating over the elements.

So if you are defining a constant set of values that you need to just iterate to then tuples should be the better choice for you.

4. You can’t create a dictionary with lists as keys.

Take the following example –

Code:

{[“John”, “Doe”] : “London”}

Will result in error –

Output:

Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
TypeError: unhashable type: ‘list’

You can use tuples for this without any problem.

{(“John”, “Doe”) : “London”}

Tuples are also used as equivalent to the dictionary without keys.

[(“red”, 1), (“green”, 2), (“blue”, 3)]

Summary

That was all about the Python tuples vs lists discussion.

We saw the different syntax of tuples and lists and the mutability of these collections which is the major difference in them. We saw all the methods that are available for lists and tuples. In the end, we discussed how we can use tuples and lists effectively depending on different situations.