In this guide, you’ll learn the similarities and differences between Python tuples and lists. You’ll also understand when you should use a tuple.

List and tuples are both built-in data structures in Python. They can be used to store a collection of elements.

From support for indexing and slicing to containing heterogeneous data types, tuples and lists may appear to have similar functionality. Therefore, understanding the similarities and differences between the two can help you decide which data structure to use.

Let’s begin.

👩🏽‍💻 You can start a Python REPL and follow along with this tutorial. You can also use Geekflare’s online Python editor to code along.

Python Tuple vs List: What are the Similarities?

Let’s start by learning the similarities between lists and tuples. To facilitate better learning, we present examples of both lists and tuples.

python-tuple-vs-list

#1. Python Iterables

In Python, lists are enclosed in a pair of square brackets, whereas tuples are enclosed in parentheses. You can also create a tuple as a set of values separated by commas—without the parentheses.

They are both iterables; so you can loop through them using a for loop. 

The code cell below shows how to iterate through a list.

nums = [2,6,7,10]
print(f"Type of nums is {type(nums)}")
for num in nums:
  print(num)

# Output
Type of nums is <class 'list'>
2
6
7
10

As explained below, you can also iterate through a tuple using a loop

nums = (2,6,7,10)

# Note: nums = 2,6,7,10 is a valid tuple as well. If needed, run a quick check!

print(f"Type of nums is {type(nums)}")
for num in nums:
  print(num)

# Output
Type of nums is <class 'tuple'>
2
6
7
10

#2. Support for Creation from Other Sequences

The next similarity between lists and tuples is that they can be created from existing sequences such as strings.

sample_str = "Coding!"

The following code cell shows how list(string) returns a list, whose list items are the characters in the string.

list_from_str = list(sample_str)
print(list_from_str)

# Output
['C', 'o', 'd', 'i', 'n', 'g', '!']

Similarly, a tuple can be created from a string or other sequence using tuple(sequence). The code cell below shows how you can do it.

tuple_from_str = tuple(sample_str)
print(tuple_from_str)

# Output
('C', 'o', 'd', 'i', 'n', 'g', '!')

#3. Support for Indexing and Slicing

Python supports zero indexing in which the first element is at index zero, the second at index one, and so on. Python also supports negative indexing, where the last element is at index -1, the second-to-last element is at index -2, and so on.

list_from_str = ['C', 'o', 'd', 'i', 'n', 'g', '!']
print(list_from_str[1])
# o

The item at index -2 is the second-to-last item, ‘g’.

tuple_from_str = ('C', 'o', 'd', 'i', 'n', 'g', '!')
print(tuple_from_str[-2])
# g

You can use slicing when you want to work with a small section of the list or tuple. list[start:end] returns a slice of the list starting at the index start and extending up to end – 1. The default value for a start is 0, and the end is the last element in the iterable.

You can slice tuples using the same syntax. Let’s create slices of the list and tuple that we created earlier.

list_from_str = ['C', 'o', 'd', 'i', 'n', 'g', '!']
print(list_from_str[0:5])

['C', 'o', 'd', 'i', 'n']

In addition to the start and end values, you can also specify a step value. tuple(start:end:step) returns a slice of the tuple from start up to end - 1, in steps of step.

tuple_from_str = ('C', 'o', 'd', 'i', 'n', 'g', '!')
print(tuple_from_str[::2])

('C', 'd', 'n', '!')

Here, we set the step value to 2. So the slice contains every second element.

#4. Collections of Multiple Data Types

In the examples we’ve considered, all items on the list and tuples were of the same data type.

However, you can store values of different data types within a single list or a tuple.

The code snippet below student_list contains a student’s name as a string, age as an integer, and marks secured as a float.

student_list = ["John",22,96.5]
for item in student_list:
  print(f"{item} is of type {type(item)}")

# Output
John is of type <class 'str'>
22 is of type <class 'int'>
96.5 is of type <class 'float'>

We can come up with a similar example for a tuple.

student_tuple = ("Jane",23,99.5)
for item in student_tuple:
  print(f"{item} is of type {type(item)}")

# Output
Jane is of type <class 'str'>
23 is of type <class 'int'>
99.5 is of type <class 'float'>

#5. Support for Membership Testing

Both lists and tuples allow you to perform membership testing for the presence of certain items. If you want to check if a specific item is present in a list or a tuple, you can use the in operator.

The expression item in iterable evaluates to True if the iterable contains the item; else, False.

"Alex" in student_list
# False

"Jane" in student_tuple
# True

So far, you’ve learned the similarities between lists and tuples in Python. Next, let’s learn the key differences between the two data structures.

Python Tuple vs List: What are the Differences?

#1. Mutability of Lists and Immutability of Tuples in Python

The most crucial difference between a list and a tuple in Python is that a tuple is immutable. This means you cannot modify a tuple in place.

▶️ Here’s an example.

tuple1 = ("Java","Python","C++")
tuple1[0] = "Rust"

# Output
----> 2 tuple1[0] = "Rust"

TypeError: 'tuple' object does not support item assignment

A list is a mutable data structure, so we can modify the list by changing an item at a specific index, as in the following code cell.

list1 = ["Java","Python","C++"]
list1[0] = "Rust"
print(list1)

# Output
['Rust', 'Python', 'C++']

#2. Variable Length Lists vs Fixed Length Tuples

Python list is a variable-length data structure.

You can do the following:

  • Add an item to the end of the list
  • Add items from another list to the end of the current list
  • Remove items at a specific index from the list
list1 = [2,3,4,5]

# add an item to the end
list1.append(9)
print(list1)

# add items from list2 to the end of list1
list2 = [0,7]
list1.extend(list2)
print(list1)

# remove an item from list1
list1.pop(0)
print(list1)

▶️ The output of the above code snippet.

# Output
[2, 3, 4, 5, 9]
[2, 3, 4, 5, 9, 0, 7]
[3, 4, 5, 9, 0, 7]

Tuples are fixed-length data structures. So you cannot add or remove elements from an existing tuple. But you can redefine the tuple to contain different elements.

tuple1 = (2,4,6,8)
tuple1 = (1,8,9)
print(tuple1)

# Output
(1, 8, 9)

#3. Size in Memory

We’ll now build on top of what we learned in the previous section: the list is a variable-length data structure.

When you define the list initially, a specific size is allocated for it in memory. Now, when you modify a list using the append() or extend() methods, additional memory should be allocated to store the added elements. This allocation is almost always done more than the number of items you add.

So there’s a need to keep track of the number of items on the list and the allocated space. In addition, as lists are variable length, there’s a pointer that points to the address of the list items. As a result, lists of length k take up more memory than a tuple with the same k elements.

Here’s a simple illustration.

python-tuple-vs-list-size

You can use the built-in sys module’s getsizeof() method on a Python object to get the size of an object in memory.

import sys

list1 = [4,5,9,14]
list_size = sys.getsizeof(list1)
print(f"Size of list:{list_size}")

tuple1 = (4,5,9,14)
tuple_size = sys.getsizeof(tuple1)
print(f"Size of tuple:{tuple_size}")

A list takes up more memory than a tuple for the same number and value of elements, as verified in the output below.

# Output
Size of list:104
Size of tuple:88
tuple-vs-list-python

When Should You Use a Python Tuple?

From the differences and similarities between Python lists and tuples, you know that if you need a mutable collection, you should use a list.

But when should you use a tuple instead?

We’ll go over that in this section.

#1. Read-Only Collection

Whenever you want a collection to be immutable, you should define it as a tuple. Suppose color = (243,55,103)  a tuple containing the RGB values corresponding to a color shade. Defining color as a tuple ensures that it cannot be modified.

In essence, when you need a collection to be read-only: values should not be modified during the program, you should consider using a tuple. This will prevent unintended modification of the values.

#2. Dictionary Keys

For example, you create a dictionary using the list items key_list as the keys. You can use the dict.fromkeys() method to create a dictionary from a list.

key_list = list("ABCD")
dict.fromkeys(key_list)

{'A': None, 'B': None, 'C': None, 'D': None}

Suppose you modify the list to contain ‘D’ as the first element (index 0)—before creating the dictionary.

Now, what happens to the dictionary key ‘A’?

If you try to create a dictionary from key_list and access the value corresponding to the key ‘A’, you’ll run into a KeyError.

key_list[0] = 'D'

dict.fromkeys(key_list)['A']

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-c90392acc2cf> in <module>()
----> 1 dict.fromkeys(key_list)['A']

KeyError: 'A'

The keys of a dictionary should be unique. So you cannot have a second ‘D’  as a key.

dict.fromkeys(key_list)
{'B': None, 'C': None, 'D': None} # A is no longer a key.

If you instead use a tuple, such modification is impossible, and you’re less likely to run into errors. Therefore, you should prefer creating a dictionary using the items of a tuple as keys.

key_tuple = tuple("ABCD")
dict.fromkeys(key_tuple)
{'A': None, 'B': None, 'C': None, 'D': None}

key_tuple[0] = 'D'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-2cecbefa7db2> in <module>()
----> 1 key_tuple[0] = 'D'

TypeError: 'tuple' object does not support item assignment

#3. Function Arguments

The immutability of tuples also makes them suitable to be passed in as function arguments.

Consider the following function find_volume() that returns the volume of a cuboid given the dimensions: length, breadth, and height.

def find_volume(dimensions):
  l,b,h = dimensions
  return l*b*h

Suppose these dimensions are available in a list called dimensions. The call to find_volume() with dimensions as the argument returns the volume.

dimensions = [2,8,5]
find_volume(dimensions)
80

You can always change the dimensions stored in a list.

dimensions = [20,8,5]
find_volume(dimensions)
800

However, sometimes you’ll need the values to remain constant and resist modification. That’s when you should consider storing the arguments as a tuple and using them in the function call.

#4. Return Values from Functions

In Python, you’ll come across tuples in return values from functions. When you return multiple values from a function, Python implicitly returns them as a tuple.

Consider the following function return_even():

def return_even(num):
  even = [i for i in range(num) if (i%2==0)]
  return even,len(even)
  • It takes a number num as the argument
  • It returns the list of even numbers in the interval [0,num) and the length of that list.

Let’s set the value of num 20 and call the function.

num = 20

Calling return_even() returns the two values in a tuple. You can call the type() function with the function call as the verification argument.

type(return_even(num)) # <class 'tuple'>

You can print out the return value to verify that it’s a tuple containing the list of even numbers as the first item and the length of the list as the second item.

print(return_even(num))
([0, 2, 4, 6, 8, 10, 12, 14, 16, 18], 10)

As there are two items in the tuple, you can unpack them into two variables, as shown below.

even_nums, count = return_even(num)

print(even_nums)
print(count)

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
10

Conclusion

I hope this tutorial provided a comprehensive comparison of Python tuple vs list.

Let’s wrap up the tutorial with a quick summary:

  • List and tuples are built-in data structures in Python.
  • Similarities: iterables, support for indexing, slicing, different data types, and operator for membership testing.
  • Key difference: Lists are mutable, and tuples are immutable. 
  • Other differences: Fixed length of tuples and variable length of lists, smaller size in memory of tuples.
  • When should you use a tuple? For immutable collections, dictionary keys, and function arguments.

Next, check out Python projects to practice and learn. Or learn methods to remove duplicate items from Python lists. Happy learning! then, happy coding!👩🏽‍💻