Are tuples more efficient than lists?

Summary: in this tutorial, you’ll learn the difference between tuple and list.

Both tuple and list are sequence types. However, they have some main differences.

1] A tuple is immutable while a list is mutable

The following example defines a list and modifies the first element:

fruits = ['apple', 'orange', 'banana'] fruits[0] = 'strawberry' print[fruits]

Code language: PHP [php]

Output:

['strawberry', 'orange', 'banana']

Code language: JSON / JSON with Comments [json]

As you can see clearly from the output, you can mutable a list. However, you cannot mutable a tuple. The following will result in an error:

fruits = ['apple', 'orange', 'banana'] fruits[0] = 'strawberry'

Code language: JavaScript [javascript]

Error:

TypeError: 'tuple' object does not support item assignment

Code language: JavaScript [javascript]

Python doesn’t you to change the element of a tuple. But you can reference a new tuple. For example:

fruits = ['apple', 'orange', 'banana'] fruits = ['strawberry', 'orange', 'banana']

Code language: JavaScript [javascript]

In this example, Python creates a new tuple and bounds the fruits variable to the newly created tuple.

If you examine the memory addresses of the tuple objects, you’ll see that the fruits variable references a different memory address after the assignment:

fruits = ['apple', 'orange', 'banana'] print[hex[id[fruits]]] fruits = ['strawberry', 'orange', 'banana'] print[hex[id[fruits]]]

Code language: PHP [php]

Output:

0x1c018286e00 0x1c018286e40

2] The storage efficiency of a tuple is greater than a list

A list is mutable. It means that you can add more elements to it. Because of this, Python needs to allocate more memory than needed to the list. This is called over-allocating. The over-allocation improves performance when a list is expanded.

Meanwhile, a tuple is immutable therefore its element count is fixed. So Python just needs to allocate enough memory to store the initial elements.

As a result, the storage efficiency of a tuple is greater than a list.

To get the size of an object, you use the getsizeof function from the sys module.

The following shows the sizes of a list and a tuple that stores the same elements:

from sys import getsizeof fruits = ['apple', 'orange', 'banana'] print[f'The size of the list is {getsizeof[fruits]} bytes.'] fruits = ['strawberry', 'orange', 'banana'] print[f'The size of the tuple is {getsizeof[fruits]} bytes.']

Code language: JavaScript [javascript]

Output:

The size of the list is 80 bytes. The size of the tuple is 64 bytes.

Code language: PHP [php]

3] Copying a tuple is faster than a list

When you copy a list, Python creates a new list. The following example illustrates copying a list to another:

fruit_list = ['apple', 'orange', 'banana'] fruit_list2 = list[fruit_list] print[id[fruit_list] == id[fruit_list2]]

Code language: PHP [php]

However, when copying a tuple, Python just reuses an existing tuple. It doesn’t create a new tuple because tuples are immutable.

fruit_tuple = ['apple', 'orange', 'banana'] fruit_tuple2 = tuple[fruit_tuple] print[id[fruit_tuple] == id[fruit_tuple2]]

Code language: PHP [php]

Therefore, copying a tuple always slightly faster than a list.

The following compares the time that needs to copy a list and a tuple 1 million times:

from timeit import timeit times = 1_000_000 t1 = timeit["list[['apple', 'orange', 'banana']]", number=times] print[f'Time to copy a list {times} times: {t1}'] t2 = timeit["tuple[['apple', 'orange', 'banana']]", number=times] print[f'Time to copy a tuple {times} times: {t2}'] diff = "{:.0%}".format[[t2 - t1]/t1] print[f'difference: {diff}']

Code language: PHP [php]

Summary

  • A tuple is immutable while a list is mutable.
  • The storage efficiency of a tuple is greater than a list.
  • Copying a tuple is slightly faster than a list.
  • Use a tuple if you don’t intend to mutable it.

Did you find this tutorial helpful ?

List in python is simply a collection which is ordered and changeable. Lists can contain multiple datatypes. It can be created by putting the elements between the square brackets.

myList = ['mango', 'apple', 'orange']

What is a tuple

Much like list, tuple is also a collection of ordered elements that can contain elements of multiple datatypes. However, tuple is a immutable. This effectively means that you cannot edit or delete an element of a tuple. Tuple can be created by putting elements between round brackets.

myTuple = ['Red', 'Black', 'White']

There is a common perception that tuples are lists that are immutable. However it is not completely true.

Why should lists be used for homogeneous data and tuple for heterogeneous data?

Is this really true? is this a guideline? no.. no.. in reality both of them are heterogeneous collections. You are free to use tuples for homogeneous data and lists for heterogeneous data. It is more of a culture than a guideline.

  • Main reason why list is preferred for homogeneous data is because it is mutable
  • If you have list of several things of same kind, it make sense to add another one to the list or take one from it. You are still left with a list of same things

But why is tuple different?

  • If you have a set of heterogeneous elements, most probably the collection has a fixed structure or ‘schema’.
#schema of tuple => [person name, age, weight] StudentDetails = ['Job John', 35, 72]
  • In other words, tuples can be used to store records — related information that belong together
  • In such cases, tuple lets us “chunk” together related information and use it as a single entity.
  • Since tuple is immutable, it can be used as key for dictionary

Why is tuple faster than list?

Program execution is faster when manipulating a tuple than for a list of same size. However, it is not noticeable for collections of smaller size.

Whats the problem with list, anyway?

List has a method called append[] to add single items to the existing list. So, for most of the append to be fast, python actually create a larger array in memory every time you create a list — in case you append.

This way when append is called, it doesn’t have to recreate the list.

Thus, making a list of five elements will cost more than five elements worth of memory.

What does tuple do?

In contrary, since tuple is immutable, it asks for an immutable structure. This way tuples are more explicit with memory.

Thus, making a tuple of five elements will cost only five elements worth of memory.

Finally, this overhead with memory for list costs its speed.

“If you want to define a constant set of values and the only thing you want to do with it is to iterate through them, then use tuple than a list.”

Thank you for reading my article, If you liked this one, you might also like the below articles,

Acknowledgments

The main image from this piece is a Photo by Julia Joppien on Unsplash

Video liên quan

Chủ Đề