Python Tuples vs Lists – Comparison Between Lists and Tuples

Free Python courses with 57 real-time projects - Learn Python

1. Python Tuples vs Lists  – Objective

In our previous python tutorials, we’ve seen tuples in python and lists in python. Both are heterogeneous collections of python objects. But which one do you choose when you need to store a collection? To answer this question, we first get a little deeper into the two constructs and then we will study comparison between python tuples vs lists.

So, let’s start Python Tuples vs Lists Tutorial.

python tuples vs lists

Python Tuples vs Lists – Comparison between Lists and Tuples

2. A Revision of Tuples in Python

Before comparing tuples and lists, we should revise the two. First, we look at a tuple.
A tuple is a collection of values, and we declare it using parentheses. However, we can also use tuple packing to do the same, and unpacking to assign its values to a sequence of variables.

>>> numbers=(1,2,'three')
>>> numbers=4,5,6
>>> a,b,c=numbers
>>> print(numbers,a,b,c,type(numbers))

(4, 5, 6) 4 5 6 <class ‘tuple’>

A tuple is returned when we call the method localtime().

>>> import time
>>> time.localtime()

time.struct_time(tm_year=2018, tm_mon=1, tm_mday=1, tm_hour=23, tm_min=1, tm_sec=59, tm_wday=0, tm_yday=1, tm_isdst=0)

To access a tuple, we use indexing, which begins at 0.

>>> numbers[1]

5

We can also slice it to retrieve a part of it.

>>> numbers[:-1]

(4, 5)

Finally, we can delete an entire tuple.

>>> del numbers
>>> numbers

Traceback (most recent call last):

File “<pyshell#40>”, line 1, in <module>

numbers

NameError: name ‘numbers’ is not defined

We also learned some functions and methods on tuples and lists. You must read our tutorials on them for more insight.

3. A Revision of Lists in Python

Unlike in C++, we don’t have arrays to work with in Python. Here, we have a list instead.

We create lists using square brackets.

>>> colors=['red','blue','green']

We can slice lists too.

>>> colors[-2:]

[‘blue’, ‘green’]

Then, we learned how to reassign and delete them.

>>> colors[0]='pink'
>>> colors

[‘pink’, ‘blue’, ‘green’]

>>> del colors[0]
>>> colors[0]

‘blue’

>>> del colors
>>> colors

Traceback (most recent call last):

File “<pyshell#52>”, line 1, in <module>

colors

NameError: name ‘colors’ is not defined

Now that we’ve refreshed our memories, we can proceed to differentiate between python tuples vs lists.

4. Python tuples vs lists – Mutability

The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means that a list can be changed, but a tuple cannot.

a. A List is Mutable

Let’s first see lists. Let’s take a new list for exemplar purposes.

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

Now first, we’ll try reassigning an element of a list. Let’s reassign the second element to hold the value 3.

>>> list1[1]=3
>>> list1

[0, 3, 2, 3, 4, 5, 6, 7]

Again, let’s see how we can reassign the entire list.

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

[7, 6, 5, 4, 3, 2, 1, 0]

It worked, great.

Now, we will delete just one element from the list.

>>> del list1[1]
>>> list1

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

This was easy, but could we delete a slice of the list? Let’s try it.

>>> del list1[3:]
>>> list1

[7, 5, 4]

We can access a slice the same way. Can we reassign a slice?

>>> nums=[1,2,3,4,5]
>>> nums[1:3]=[6,7,8]
>>> nums

[1, 6, 7, 8, 4, 5]

Indeed, we can. Finally, let’s try deleting the entire list.

>>> del list1
>>> list1

Traceback (most recent call last):

File “<pyshell#67>”, line 1, in <module>

list1

NameError: name ‘list1’ is not defined

The list doesn’t exist anymore.

b. A Tuple is Immutable

Now, let’s try doing the same things to a tuple. We know that a tuple is immutable, so some of these operations shouldn’t work. We’ll take a new tuple for this purpose.

>>> mytuple=0,1,2,3,4,5,6,7

First, let’s try reassigning the second element.

>>> mytuple[1]=3

Traceback (most recent call last):

File “<pyshell#70>”, line 1, in <module>

mytuple[1]=3

TypeError: ‘tuple’ object does not support item assignment

As you can see, a tuple doesn’t support item assignment.

However, we can reassign an entire tuple.

>>> mytuple=2,3,4,5,6
>>> mytuple

(2, 3, 4, 5, 6)

Next, let’s try slicing a tuple to access or delete it.

>>> mytuple[3:]

(5, 6)

>>> del mytuple[3:]

Traceback (most recent call last):

File “<pyshell#74>”, line 1, in <module>

del mytuple[3:]

TypeError: ‘tuple’ object does not support item deletion

As is visible, we can slice it to access it, but we can’t delete a slice. This is because it is immutable.

Can we delete a single element?

>>> del  mytuple[3]

Traceback (most recent call last):

File “<pyshell#75>”, line 1, in <module>

del  mytuple[3]

TypeError: ‘tuple’ object doesn’t support item deletion

Apparently, the answer is no.

Finally, let’s try deleting the entire tuple.

>>> del  mytuple
>>> mytuple

Traceback (most recent call last):

File “<pyshell#77>”, line 1, in <module>

mytuple

NameError: name ‘mytuple’ is not defined

So, here, we conclude that you can slice a tuple, reassign it whole, or delete it whole.

But you cannot delete or reassign just a few elements or a slice.

Let us proceed with more differences between python tuples vs lists.

5. Functions

Some python functions apply on both, these are- len(), max(), min(), sum(), any(), all(), sorted(). We’ll take just one example here for both containers.

>>> max((1,3,-1))

3

>>> max([1,3,-1])

3

6. Methods

Lists and tuples share the index() and count() methods. But other than those, there are a few methods that apply to lists. These are- append(), insert(), remove(), pop(), clear(), sort(), and reverse(). Let’s take an example of one of these.

>>> [1,3,2].index(3)

1

>>> (1,3,2).index(3)

1
To get an insight into all of these methods and functions we mentioned, you should refer to our articles on lists and tuples.

7. Tuples in a List

We can store tuples in a list when we want to.

>>> mylist=[(1,2,3),(4,5,6)]
>>> type(mylist)

<class ‘list’>

>>> type(mylist[1])

<class ‘tuple’>

But when would we need to do this? Take an example.

[(1, ‘ABC’), (2, ‘DEF’), (3, ‘GHI’)]

8. Lists in a Tuple

Likewise, we can also use a tuple to store lists. Let’s see how.

>>> mytuple=([1,2],[3,4],[5,6])

9. Nested Tuples

A tuple may hold more tuples, and this can go on in more than two dimensions.

>>> mytuple=((1,2),(3,(4,5),(6,(7,(8,9)))))

To access the element with the value 8, we write the following code.

>>> mytuple[1][2][1][1][0]

8

10. Nested Lists

Similarly, a list may hold more lists, in as many dimensions as you want.

>>> mylist=[[1,2],[3,4]]
>>> myotherlist=[[1,2],[3,[4,5]]]

To access the element with the value 5, we write the following code.

>>> myotherlist[1][1][1]

5

11. When to Use Which

Use a tuple when you know what information goes in the container that it is. For example, when you want to store a person’s credentials for your website.

>>> person=('ABC','admin','12345')

But when you want to store similar elements, like in an array in C++, you should use a list.

>>> groceries=['bread','butter','cheese']

Note that this does not say that a list can only contain homogeneous values. Also, you can’t use a list as a key for a dictionary. This is because only immutable values can be hashed. Hence, we can only set immutable values like tuples as keys. But if you still want to use a list as a key, you must turn it into a tuple first.

So, this was all about Python Tuples vs Lists. Hope you like our explanation.

12. Conclusion

Now that we know the differences between python tuples vs lists, it shouldn’t be a very tough choice between the two. The major difference is that a list is mutable, but a tuple isn’t. So, we use a list when we want to contain similar items, but use a tuple when we know what information goes into it.

What do you think? Tell us in the comments.

Reference

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

9 Responses

  1. Ivelin Ivanov says:

    Great brief comparison of Python tuples vs lists. Thank you!

    • DataFlair Team says:

      In Python language, lists and tuples are classes of Python Data Structures. List is an ordered and changeable collection of elements and a tuple is an ordered and unchangeable collection of elements. Lists are dynamic, while the tuples have static characteristics. This lists can be changed, whereas tuples can’t be changed. Tuples are faster than lists due to their static nature.

  2. Jatin says:

    Using list in Tuple??????
    Does it really make sense????
    Tuple is immutable and a
    List is mutable
    If we are using list in tuple it does not make any sense because we cannot change its values

    • Daniru says:

      >>> t = (1,2,[4,5,6])
      >>> t[2][0] = 40
      >>> t
      (1, 2, [40, 5, 6])

    • DataFlair says:

      Yes, you cannot modify a tuple you can surely modify a list even if it is an element of Tuple. Consider the below example:
      mytuple=([1,2],[3,4],[5,6])
      mytuple[1].append(3)
      print(mytuple)

      Output:
      ([1, 2], [3, 4, 3], [5, 6])

      As you can see we cannot change any element of this tuple but can modify the elements of the list.

  3. Jonas says:

    Hello Jatin,
    actually you can change the items in the list, but not the list itself. It is also described in the tuples article on this page. Hope this make sense…

  4. Jijo says:

    Hello jatin,
    When you use list in a tuple,it means that the element in the tuple is data of datatype list,which is a nested concept.you cannot delete or replace that list since it is an element of tuple.But you can make changes to the elements inside that list.
    eg:
    tuple=([1,2,3],1)
    tuple[0][0]=1#the element of the list [1,2,3] at 0 index changed to 1
    tuple[1]=1#this will rise a TypeError: ‘tuple’ object does not support item assignment

  5. Daniel says:

    For the descriptions thus far, it appears that the decision comes down to preferences rather than advantages/disadvantages of either. I can think of one personally applicable advantage to using a tuple, but haven’t found any clear guidelines and this. Maybe if you have a lot of code, and want to continually have an immutable collection such as:

    >>> userInfo = (‘john’,’paul’,’Italy’)

    this will make sure you don’t forget and change things later on when coming back to the code.

    >>> userInfo[0] = ‘mark’
    ERROR

    When starting with python, I primarily created lists, but sometimes forgot that I wanted some lists to never change, so this could MAYBE be useful in that scenario?

    • DataFlair says:

      Yes, exactly…It is recommended to use tuples when you don’t want to modify the data stored as a list intentionally or uninterntionally.

Leave a Reply

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