Lists vs Tuples in Python

Lists vs Tuples in Python

Introduction

Lists and tuples are two of the most commonly used data structures in Python, with dictionary being the third. Lists and tuples have many similarities:

  • They are both sequence data types that store a collection of items
  • They can store items of any data type
  • And any item is accessible via its index.

So the question we're trying to answer here is, how are they different? And if there is no difference between the two, why should we have the two? Can't we have either lists or tuples?

In this article, we will show how lists and tuples differ from each other.

Syntax Difference

In Python, lists and tuples are declared in different ways. A list is created using square brackets [] whereas the tuple is created using parenthesis ():

tuple_names = ('Nicholas', 'Michelle', 'Alex')
list_names = ['Nicholas', 'Michelle', 'Alex']
print(tuple_names)
print(list_names)

This will result in:

('Nicholas', 'Michelle', 'Alex')
['Nicholas', 'Michelle', 'Alex']

We defined a tuple named tuple_names and a list named list_names. In the tuple definition, we used parenthesis () while in the list definition, we used square brackets [].

Python's type() method helps easily identify the type of an object:

print(type(tuple_names)) # <class 'tuple'>
print(type(list_names)) # <class 'list'>

Mutable vs Immutable

Lists are mutable while tuples are immutable, and this marks the key difference between the two. What does this mean?

We can change/modify the values of a list but we cannot change/modify the values of a tuple.

Since lists are mutable, we can't use a list as a key in a dictionary. This is because only an immutable object can be used as a key in a dictionary. Thus, we can use tuples as dictionary keys if needed.

Let's take a look at an example that demonstrates the difference between lists and tuples in terms of immutability. Let us create a list of different names:

names = ["Nicholas", "Michelle", "Alex"]

Let us see what will happen if we attempt to change the first element of the list from Nicholas to Samuel:

names[0] = "Samuel"

Note: The first element is at index 0.

Now, let us display the contents of the list:

print(names)

This will print out the updated list:

['Samuel', 'Michelle', 'Alex']

What if we attempt to do the same with a tuple? First, let's create a tuple:

 names = ("Nicholas", "Michelle", "Alex")

Let us now attempt to change the first element of the tuple from Nicholas to Samuel:

names[0] = "Samuel"

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This will result in the following error:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    names[0] = "Samuel"
TypeError: 'tuple' object does not support item assignment

We got an error that a tuple object does not support item assignment. The reason is that a tuple object cannot be changed after it has been created.

Reused vs Copied

Tuples cannot be copied. The reason is that tuples are immutable. If you run tuple(tuple_name), it will immediately return itself:

names = ('Nicholas', 'Michelle', 'Alex')
copy_names = tuple(names)
print(names is copy_names)

The two are the same:

True

In contrast, list(list_name) requires copying of all data to a new list:

names = ['Nicholas', 'Michelle', 'Alex']
copy_names = list(names)
print(names is copy_names)

Since names and copy_names are not the same, the result is False:

False

Next, let us discuss how the list and the tuple differ in terms of size.

Size Difference

Python allocates larger blocks of memory with a low overhead to tuples because they are immutable. On the other hand, for lists, Pythons allocate small memory blocks. At the end of it, the tuple will have a smaller memory compared to the list. This makes tuples a bit more space-efficient compared to lists when you have a large number of elements.

For example, let's create a list and a tuple containing the same elements and compare the sizes of the two:

tuple_names = ('Nicholas', 'Michelle', 'Alex')
list_names = ['Nicholas', 'Michelle', 'Alex']
print(tuple_names.__sizeof__())
print(list_names.__sizeof__())

The output shows that the list has a larger size than the tuple:

48
64

Note: The size shown is in terms of bytes.

Homogeneous vs Heterogeneous

Tuples are typically used to store heterogeneous elements, which are elements belonging to different data types. Lists, on the other hand, are typically used to store homogenous elements, which are elements that belong to the same type.

Note: This is only a semantic difference. Both data types are heterogenous, but the convention differs. You can store elements of the same type in a tuple and elements of different types in a list, as well.

The following code will run with no error despite the fact that the list has a mixture of strings and a number:

list_elements = ['Nicholas', 10, 'Alex']
tuple_elements = ('Nicholas', "Michelle", 'Alex')

Variable Length vs Fixed Length

Tuples have a fixed length while lists have a variable length. This means we can change the size of a created list but we cannot change the size of an existing tuple:

list_names = ['Nicholas', 'Michelle', 'Alex']
list_names.append("Mercy")
print(list_names)

The output shows that a fourth name has been added to the list:

['Nicholas', 'Michelle', 'Alex', 'Mercy']

We have used the Python's append() method for this. We could have achieved the same via the insert() method:

list_names = ['Nicholas', 'Michelle', 'Alex']
list_names.insert(3, "Mercy")
print(list_names)

The output again shows that a fourth element has been added to the list:

['Nicholas', 'Michelle', 'Alex', 'Mercy']

A Python tuple doesn't provide us with a way to change its size.

Conclusion

We can conclude that although both lists and tuples are data structures in Python, there are remarkable differences between the two, with the main difference being that lists are mutable while tuples are immutable. A list has a variable size while a tuple has a fixed size. Operations on tuples can be executed faster compared to operations on lists.

Last Updated: April 19th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Nicholas SamuelAuthor

I am a programmer by profession. I am highly interested in Python, Java, Data Science and Machine learning. If you need help in any of these, don't hesitate to contact me.

Free
Course

Graphs in Python - Theory and Implementation

# python# data structures# algorithms# computer science

Graphs are an extremely versatile data structure. More so than most people realize! Graphs can be used to model practically anything, given their nature of...

David Landup
Dimitrije Stamenic
Jovana Ninkovic
Details

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms