Blog header background

List vs Tuple: Difference Between List and Tuple in Python

Updated on July 31, 2024

7 min read

Copy link
Share on WhatsApp

Are you confused about when to use lists and tuples in Python? Do you wonder why sometimes we need one and not the other?

Lists and tuples are both used to store collections of items. But they have some key differences.

Lists are like arrays in other languages. They can hold different types of items. Lists are created using square brackets [].

Tuples are similar but with a twist. Once created, they cannot be changed. Tuples are created using parentheses ().

Knowing these differences can help us write better code.

In this blog, we’ll dive into the specifics. We’ll learn the difference between list and tuple in Python.

Syntax and Creation of Lists and Tuples

List Syntax and Creation

Creating a list in Python is straightforward. We use square brackets [] to define a list. Here’s how we can create a list of fruits:

# Creating a list

fruits = ['apple', 'banana', 'cherry']

print(fruits)

<img decoding="async" loading="lazy" class="aligncenter size-full wp-image-317263" src="https://staging.herovired.com/wp-content/uploads/2024/07/1-21.png" alt="output" width="404" height="165" srcset="https://staging.herovired.com/wp-content/uploads/2024/07/1-21.png 404w, https://staging.herovired.com/wp-content/uploads/2024/07/1-21-300x123.png 300w" sizes="(max-width: 404px) 100vw, 404px" />

Tuple Syntax and Creation

For tuples, we use parentheses (). Let’s create a tuple of fruits:

# Creating a tuple

fruits = ('apple', 'banana', 'cherry')

print(fruits)

output

brochure-banner-bg

POSTGRADUATE PROGRAM IN

Multi Cloud Architecture & DevOps

Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.

Mutability: Why Lists Can Change and Tuples Cannot

Lists Are Mutable

Lists allow us to modify them after creation. This includes adding, removing, or changing items. Let’s look at an example:

# Modifying a list

fruits = ['apple', 'banana', 'cherry']

fruits.append('orange')

fruits[1] = 'blueberry'

print(fruits)
<img decoding="async" loading="lazy" class="aligncenter size-full wp-image-317265" src="https://staging.herovired.com/wp-content/uploads/2024/07/3-20.png" alt="output" width="473" height="190" srcset="https://staging.herovired.com/wp-content/uploads/2024/07/3-20.png 473w, https://staging.herovired.com/wp-content/uploads/2024/07/3-20-300x121.png 300w" sizes="(max-width: 473px) 100vw, 473px" />

In this example, we added ‘orange’ to the list and changed ‘banana’ to ‘blueberry’. This flexibility makes lists ideal for collections of items that might change.

Tuples Are Immutable

Tuples, on the other hand, do not allow modifications after creation. If we try to change a tuple, we will get an error. Here’s an example:

# Attempting to modify a tuple (will raise an error)

fruits = ('apple', 'banana', 'cherry')

fruits[1] = 'blueberry'  # Uncommenting this line will cause an error

print(fruits)

output

As you can also observe, the attempt to modify the data of the tuple and change ‘banana’ to ‘blueberry’ will not be possible. This makes tuples good for data that should not change because any change that is made is rejected, keeping the data consistent.

Performance Considerations: Speed and Efficiency

Are you worried about the speed of your Python code? Wondering if you should use a list or a tuple to make it faster?

In programming, speed, and efficiency can make a big difference. Tuples are generally faster than lists. Why? Because they are immutable.

This means that once a tuple is created, Python can optimise its performance better than a list.

Let’s look at an example to see the difference in speed:

import time 

# Creating a list and a tuple with 1 million elements

large_list = list(range(1000000))

large_tuple = tuple(range(1000000)) 

# Timing list iteration

start_time = time.time()

for item in large_list:

pass

end_time = time.time()

list_time = end_time - start_time 

# Timing tuple iteration

start_time = time.time()

for item in large_tuple:

pass

end_time = time.time()

tuple_time = end_time - start_time 

print(f"Time to iterate over list: {list_time} seconds")

print(f"Time to iterate over tuple: {tuple_time} seconds")

Output:

output

Memory Usage: Comparing the Memory Consumption

Are you running out of memory in your Python programs?

Tuples use less memory than lists. This is because tuples are immutable and do not need extra space for changes.

This can be crucial when working with large datasets or running code on memory-constrained devices. Let’s compare the memory usage:

import sys

# Creating a list and a tuple with a few elements

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

small_tuple = (1, 2, 3, 4, 5) 

# Checking memory size

list_size = sys.getsizeof(small_list)

tuple_size = sys.getsizeof(small_tuple) 

print(f"Memory size of list: {list_size} bytes")

print(f"Memory size of tuple: {tuple_size} bytes")

Output:

output

skill-test-section-bg

82.9%

of professionals don't believe their degree can help them get ahead at work.

Built-in Methods and Operations: What We Can Do with Lists and Tuples

Do you need to perform many operations on your data? Wondering what methods are available for lists and tuples?

Lists come with many built-in methods that make them very flexible. Here are some common list methods:

  • append(): Adds an item to the end of the list.
  • remove(): Removes the first occurrence of an item.
  • sort(): Sorts the list in place.
  • reverse(): Reverses the order of items in the list.

Example: Using list methods

# List of numbers

numbers = [3, 1, 4, 1, 5] 

# Using append

numbers.append(9)

print(numbers)  # Output: [3, 1, 4, 1, 5, 9] 

# Using remove

numbers.remove(1)

print(numbers)  # Output: [3, 4, 1, 5, 9] 

# Using sort

numbers.sort()

print(numbers)  # Output: [1, 3, 4, 5, 9] 

# Using reverse

numbers.reverse()

print(numbers)  # Output: [9, 5, 4, 3, 1]

Output:

output

Tuples have fewer methods since they are immutable. Here are some common tuple methods:

  • count(): Returns the number of occurrences of a value.
  • index(): Returns the index of the first occurrence of a value.

While lists offer more flexibility, tuples are simpler and can still perform essential tasks.

Example: Using tuple methods

# Tuple of numbers

numbers = (3, 1, 4, 1, 5) 

# Using count

print(numbers.count(1))  # Output: 2 

# Using index

print(numbers.index(4))  # Output: 2

Output:

output

Practical Use Cases: When to Use Lists Vs Tuples

Do you have confusion between a list and a tuple as to when it is preferable to use them? Here are some practical examples that would help you decide.

When to Use Lists

  • Dynamic Collections: Use lists when you need to add, remove, or change items.
  • Order Preservation: Lists maintain the order of items and allow duplicate values.
  • Flexible Operations: Lists are great for operations like sorting, reversing, and slicing.

Example: To-do list

# Creating a to-do list

to_do = ['buy groceries', 'write blog post', 'exercise']

to_do.append('read book')

print(to_do)  # Output: ['buy groceries', 'write blog post', 'exercise', 'read book']

Output:

output

When to Use Tuples

  • Fixed Collections: Use tuples for data that should not change.
  • Memory Efficiency: Tuples use less memory, making them suitable for large datasets.
  • Faster Access: Tuples can be faster to access and iterate.

Example: Geographic coordinates

# Storing coordinates as a tuple

coordinates = (40.7128, -74.0060)

print(coordinates)  # Output: (40.7128, -74.0060)

Output:

output

Sometimes, the proper selection of the data structure can lead to great optimisation of the code and a better understanding of it. Lists are an ideal medium for data that is constantly changing, while tuples are ideal data-types for data that will not be changing at all.

Debugging and Error Handling with Lists and Tuples

Has it ever happened to you to get some ‘random’ errors when working with Lists and Tuples? Debugging a code and error manipulating is sometimes a difficult task if you are not sure what to look out for.

Debugging Lists

Lists are mutable, which means they can be changed. This flexibility can sometimes lead to unexpected bugs.

Common issues with lists:

  • Index errors: Accessing an index that does not exist.
  • Mutation bugs: Unintended changes to the list.

Example:

# Index error example

fruits = ['apple', 'banana', 'cherry']

try:

print(fruits[3])  # This will raise an IndexError

except IndexError as e:

print(f"IndexError: {e}") 

# Mutation bug example

def add_fruit(fruit_list):

fruit_list.append('orange')

return fruit_list 

fruits = ['apple', 'banana', 'cherry']

new_fruits = add_fruit(fruits)

print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']

Output:

output

Debugging Tuples

Tuples, being immutable, have fewer issues related to changes. However, trying to modify a tuple will raise an error.

Common issues with tuples:

  • Type errors: Attempting to modify a tuple.
  • Index errors: Similar to lists, accessing non-existent indexes.

Example:


# Type error example

coordinates = (1, 2, 3)

try:

coordinates[0] = 0  # This will raise a TypeError

except TypeError as e:

print(f"TypeError: {e}") 

# Index error example

try:

print(coordinates[3])  # This will raise an IndexError

except IndexError as e:

print(f"IndexError: {e}")

Output:

output

Conclusion: Choosing Between Lists and Tuples

Understanding the difference between list and tuple in Python helps us write better code. It makes our programs more efficient and easier to maintain.

Here’s a quick comparison:

Feature List Tuple
Mutability Mutable Immutable
Syntax [] ()
Performance Slower Faster
Memory Usage More Less
Methods Available Many Fewer

Whether we need flexibility or stability, knowing when to use lists or tuples is key.

FAQs
Can I change the elements of a tuple after it is created?
No, tuples are immutable. We cannot change their elements after creation.
Which is faster for accessing elements, a list or a tuple?
Tuples are generally faster for accessing elements because they are immutable.
Are there any operations that can be performed on lists but not on tuples?
Yes, lists support operations like append(), remove(), and sort(), which are not available for tuples.
Can a list be used as a key in a dictionary?
No, only immutable types like tuples can be used as dictionary keys. Lists are mutable and cannot be used as keys.

Updated on July 31, 2024

Link
Loading related articles...