Lists vs. Tuples in Python: A Comprehensive Guide

Python provides several built-in data types. Two of these are Lists and Tuples. Understanding the nuances of these data structures is crucial to writing efficient and effective Python code.

By the end of this tutorial, you’ll be able to make informed decisions on when to use a list and when to opt for a tuple, enhancing your proficiency in handling data in Python.

 

 

Overview of Lists and Tuples

Before diving into Python list vs. tuple comparisons, let’s look at how to create a list and a tuple to check the difference in syntax.

List Syntax

sample_list = ['apple', 'banana', 'cherry']
print(sample_list)

Output:

['apple', 'banana', 'cherry']

The list sample_list is created with three items. Each item in the list is a string representing a type of fruit. The list is printed to the console.

Tuple Syntax

sample_tuple = ('apple', 'banana', 'cherry')
print(sample_tuple)

Output:

('apple', 'banana', 'cherry')

The tuple sample_tuple is created similarly to the list, but notice the use of parentheses instead of square brackets.

Single-Element Tuples

If you’re creating single-element tuples, it is necessary to include a trailing comma. Without the comma, Python will not recognize it as a tuple.

single_element_tuple = ('apple',)
not_a_tuple = ('apple')

print(type(single_element_tuple))
print(type(not_a_tuple))

Output:

<class 'tuple'>
<class 'str'>

 

Mutable Lists vs. Immutable Tuples

In Python, the primary difference between lists and tuples lies in their mutability. A list is mutable, meaning the data stored in lists can be changed.

On the other hand, tuples are immutable, i.e., they cannot be modified once created.
Here is an example of how lists can be modified:

sample_list = ['apple', 'banana', 'cherry']
sample_list[1] = 'blueberry'
print(sample_list)

Output:

['apple', 'blueberry', 'cherry']

We replaced the second item (index 1) in the list (‘banana’) with ‘blueberry’. As you can see, lists are dynamic; we can modify them after creation.
On the contrary, if we attempt to modify a tuple, Python will raise an error:

sample_tuple = ('apple', 'banana', 'cherry')
sample_tuple[1] = 'blueberry'
print(sample_tuple)

Output:

TypeError: 'tuple' object does not support item assignment

This error arises because tuples cannot be modified.

 

Performance: They are the same

When accessing an element in a list or tuple by index in Python is generally an O(1) operation, meaning it takes constant time regardless of the size of the list or tuple.

I performed the following test to check which is faster:

import timeit
large_list = list(range(1000000))
large_tuple = tuple(range(1000000))

list_time = timeit.timeit('large_list[999999]', globals=globals(), number=10000)
print("Accessing an element at the end of the list for 10000 times took", list_time, "seconds")

tuple_time = timeit.timeit('large_tuple[999999]', globals=globals(), number=10000)
print("Accessing an element at the end of the tuple for 10000 times took", tuple_time, "seconds")

Output:

Accessing an element at the end of the list for 10000 times took 0.0006645999965257943 seconds
Accessing an element at the end of the tuple for 10000 times took 0.0007328999927267432 seconds

I used timeit to measure the execution time of the single-line Python statement provided as the first argument.

The globals=globals() argument ensures that timeit has access to the global namespace, so it can see large_list and large_tuple.

The number=10000 argument specifies that the code should be run 10,000 times, and the time reported is the total time for all runs.

From the output, we can see that accessing an element at the end of the tuple or a list are almost the same.

 

Memory Usage: Tuples are efficient

Lists and tuples in Python are both sequence types that can store data.

Tuples use memory more efficiently due to how they are stored in memory.
Because of their immutability, tuples can be more memory efficient than lists when they contain a large number of elements.

Python can optimize the storage of tuples by not over-allocating memory for them since it knows they can’t change in size.

The efficiency comes from the potential over-allocation that lists might use to make element addition/removal efficient, which is not needed for tuples due to their immutability.
Here’s an example to illustrate this:

import sys
sample_list = ['apple', 'banana', 'cherry']
sample_tuple = ('apple', 'banana', 'cherry')
print("Size of the list: ", sys.getsizeof(sample_list))
print("Size of the tuple: ", sys.getsizeof(sample_tuple))

Output:

Size of the list: 88
Size of the tuple: 64

In the output, you can see that the size of the tuple is smaller than that of the list, even though they contain the same elements.

This is due to the lower memory overhead that tuples have.

 

Python Tuples as Dictionary Keys

One significant difference between lists and tuples is that tuples can be used as keys in dictionaries, while lists cannot.

This is because only immutable objects can be used as a key in a dictionary in Python, and tuples are immutable.
Here’s an example:

fruit_colors = {('apple',): 'red', ('banana',): 'yellow'}
print(fruit_colors[('apple',)])

Output:

'red'

In this example, we’ve used a tuple instead of a list as a key in a dictionary. We created a dictionary named fruit_colors where the keys are tuples, and the corresponding values are colors of the fruits. Then we accessed the color of ‘apple’ using the tuple key.
Now, let’s try using a list as a key:

fruit_colors = {['apple']: 'red', ['banana']: 'yellow'}
print(fruit_colors[['apple']])

Output:

TypeError: unhashable type: 'list'

As you can see, trying to use a list as a key in a dictionary results in a TypeError.

 

Why Tuples Can Be Dictionary Keys and Lists Cannot

When we try to use a list as a key in a dictionary above we get TypeError: unhashable type.

This brings us to the concept of hashability in Python data structures. A hash is a fixed size integer that identifies a particular value.

Only immutable objects are hashable in Python, which is why tuples can be used as keys in a dictionary, and lists cannot.
Here’s an example demonstrating this:

print("Hash of the tuple: ", hash(('apple', 'banana', 'cherry')))

Output:

Hash of the tuple: 523138717648136859

Here, we created a hash for the tuple ('apple', 'banana', 'cherry'), which gives us a unique integer. This demonstrates that tuples are hashable.
However, if we try to create a hash for a list:

print("Hash of the list: ", hash(['apple', 'banana', 'cherry']))

Output:

TypeError: unhashable type: 'list'

Python throws a TypeError because lists are not hashable and hence they cannot be used as dictionary keys.

 

Lists vs. Tuples

Here is a summary table of the key differences between lists and tuples:

Feature List Tuple
Mutability Lists are mutable, i.e., they can be modified after creation. Tuples are immutable, i.e., they cannot be modified after creation.
Performance Same performance regardless of the size. Same performance regardless of the size.
Memory Usage Lists consume more memory because they are dynamic and allocate extra memory for adding or removing elements. Tuples consume less memory as they are immutable and have a fixed size.
Dictionary Keys Lists cannot be used as keys in a dictionary because they are mutable. Tuples can be used as keys in a dictionary because they are immutable.
Data Security Lists are less secure because they can be modified. Tuples are more secure as they are immutable.
Single-element Initialization A list with a single element does not require any special syntax. A tuple with a single element requires a trailing comma to be recognized as a tuple.

 

When to Use Lists and When to Use Tuples

To summarize, the decision to use a list or a tuple depends on the situation and the nature of the data:

  • Use a list when you need a collection of items that might need to change – lists are dynamic, mutable, and allow for flexible data manipulation.
  • Use a tuple when you have a collection of items that won’t change – tuples are immutable, use less memory, and can be used as keys in dictionaries, providing a higher level of data security and integrity.

Remember that while the differences between a list and a tuple may seem subtle, understanding these differences and knowing when to use each can help you write more efficient and effective Python code.

Leave a Reply

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