The Wayback Machine - https://web.archive.org/web/20241126213332/https://www.geeksforgeeks.org/python-difference-between-list-and-tuple/
Open In App

Difference Between List and Tuple in Python

Last Updated : 20 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Lists and Tuples in Python are two different implementations of array data structure.

  • List is Mutable and Tuple is not (Cannot update an element, insert and delete elements)
  • Tuples are faster because of read only nature. Memory can be efficiently allocated and used for tuples.

Differences between List and Tuple in Python

Sno

LIST

TUPLE

1Lists are mutableTuples are immutable
2The implication of iterations is Time-consumingThe implication of iterations is comparatively Faster
3The list is better for performing operations, such as insertion and deletion.A Tuple data type is appropriate for accessing the elements
4Lists consume more memoryTuple consumes less memory as compared to the list
5Lists have several built-in methodsTuple does not have many built-in methods.
6Unexpected changes and errors are more likely to occurBecause tuples don’t change they are far less error-prone.

 Python List vs Python Tuple

Test whether tuples are immutable and lists are mutable

Here we are going to compare the list and tuple mutability tests.

Python
# Creating a List with
# the use of Numbers
# code to test that tuples are mutable
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("Original list ", List)

List[3] = 77
print("Example to show mutability ", List)

Output
Original list  [1, 2, 4, 4, 3, 3, 3, 6, 5]
Example to show mutability  [1, 2, 4, 77, 3, 3, 3, 6, 5]

We can see here tuple can not be modified.

Python
# code to test that tuples are immutable

tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)

Output:

Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment

Which is better list or tuple in Python?

To put this answer to the test, let’s run some operations on a Python Tuple and a Python List. This will give us a better idea of which is a better list or tuple in Python.

Test whether Tuples are Memory Efficient

As tuples are stored in a single memory block therefore they don’t require extra space for new objects whereas the lists are allocated in two blocks, first the fixed one with all the Python object information and second a variable-sized block for the data.

Python
import sys
a_list = []
a_tuple = ()
a_list = ["Geeks", "For", "Geeks"]
a_tuple = ("Geeks", "For", "Geeks")
print(sys.getsizeof(a_list))
print(sys.getsizeof(a_tuple))

Output
96
80

Test whether the implication of iterations is comparatively faster in Tuples

As tuples are stored in a single memory block, therefore, they don’t require extra space for new objects as they are immutable whereas the lists are allocated in two blocks, first the fixed one with all the Python object information and second a variable-sized block for the data which makes them even faster.

Python
# code
import sys, platform
import time

l=list(range(100000001))
t=tuple(range(100000001))

start = time.time_ns()
for i in range(len(t)):
    a = t[i]
end = time.time_ns()
print("Total lookup time for Tuple: ", end - start)

start = time.time_ns()
for i in range(len(l)):
    a = l[i]
end = time.time_ns()
print("Total lookup time for LIST: ", end - start)

Output

Total lookup time for Tuple:  7038208700
Total lookup time for LIST: 19646516700

Mutable List vs. Immutable Tuples

In Python, both lists and tuples support a range of operations, including indexing, slicing, concatenation, and more. However, there are some differences between the operations that are available for lists and tuples due to their mutability and immutability, respectively.

Python Indexing

 Both lists and tuples allow you to access individual elements using their index, starting from 0.

Python
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)

print(my_list[0]) # Output: 1
print(my_tuple[1]) # Output: 5

Output
1
5

Python Slicing

Both lists and tuples allow you to extract a subset of elements using slicing.

Python
my_list = [1, 2, 3, 4, 5]
my_tuple = (6, 7, 8, 9, 10)

print(my_list[1:3]) # Output: [2, 3]
print(my_tuple[:3]) # Output: (6, 7, 8)

Output
[2, 3]
(6, 7, 8)

Python Concatenation

Both lists and tuples can be concatenated using the “+” operator.

Python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
tuple1 = (7, 8, 9)
tuple2 = (10, 11, 12)

print(list1 + list2) # Output: [1, 2, 3, 4, 5, 6]
print(tuple1 + tuple2) # Output: (7, 8, 9, 10, 11, 12)

Output
[1, 2, 3, 4, 5, 6]
(7, 8, 9, 10, 11, 12)

Note – However, there are some operations that are available only for lists, due to their mutability. 

Python Append

Lists can be appended with new elements using the append() method.

Python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

Output
[1, 2, 3, 4]

Python Extend

Lists can also be extended with another list using the extend() method.

Python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

Output
[1, 2, 3, 4, 5, 6]

Python Remove

Lists can have elements removed using the remove() method. 

Python
my_list = [1, 2, 3, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 4]

Output
[1, 3, 4]

When to Use Tuples Over Lists?

In Python, tuples and lists are both used to store collections of data, but they have some important differences. Here are some situations where you might want to use tuples instead of lists – 

Immutable Data – Tuples are immutable, thus once they are generated, their contents cannot be changed. This makes tuples a suitable option for storing information that shouldn’t change, such as setup settings, constant values, or other information that should stay the same while your programme is running.

Performance – Tuples are more lightweight than lists and might be quicker to generate, access, and iterate through since they are immutable. Using a tuple can be more effective than using a list if you have a huge collection of data that you need to store, retrieve, and use regularly and that data does not need to be altered.

Data integrity – By ensuring that the data’s structure and contents stay consistent, tuples can be utilised to ensure data integrity. To make sure the caller is aware of how much data to expect, for instance, if a function returns a set amount of values, you might want to return them as a tuple rather than a list.



Previous Article
Next Article

Similar Reads

Differences and Applications of List, Tuple, Set and Dictionary in Python
Python provides us with several in-built data structures such as lists, tuples, sets, and dictionaries that store and organize the data efficiently. In this article, we will learn the difference between them and their applications in Python. Table of Content Difference between List, Tuple, Set, and DictionaryPython ListApplications of Python ListPy
11 min read
Difference between Tuple Relational Calculus (TRC) and Domain Relational Calculus (DRC)
When you work on Relational Calculus which is the main concept in Database Theory, you will find two kinds of variations that play an important role. These two variations are Tuple Relational Calculus (TRC) and Domain Relational Calculus (DRC). If you want to retrieve data from the database, both TRC and DRC can be used. However, you will find many
5 min read
Python | Count the elements in a list until an element is a Tuple
In this problem, we need to accept a list. The list can have nested tuples. We need to count the elements in a list until a tuple has been encountered. Examples: Input : [4, 5, 6, 10, (1, 2, 3), 11, 2, 4] Output : 4 Input : [4, (5, 6), 10, (1, 2, 3), 11, 2, 4] Output : 1 Method #1: In this program we will use the concept of isinstance() to verify w
2 min read
Python | Ways to iterate tuple list of lists
List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.Given a tuple list of lists, write a Python program to iterate through it and get all elements. Method #1: Use itertools.ziplongest C
5 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Python | sort list of tuple based on sum
Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using the technique of Bubble Sort to we can perform the s
4 min read
Python - Find first element by second in tuple List
Sometimes, while working with Python records, we can have a problem in which we need to find the first element of tuple from the given second element. This kind of problem can occur in domains such as web development. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5), (5, 6), (1, 3), (6, 6)] K = 6 Output :
4 min read
Transpose Dual Tuple List in Python
Sometimes, while working with Python tuples, we can have a problem in which we need to perform tuple transpose of elements i.e, each column element of dual tuple becomes a row, a 2*N Tuple becomes N * 2 Tuple List. This kind of problem can have possible applications in domains such as web development and day-day programming. Let's discuss certain w
5 min read
Python List VS Array VS Tuple
List: A list is of an ordered collection data type that is mutable which means it can be easily modified and we can change its data values and a list can be indexed, sliced, and changed and each element can be accessed using its index value in the list. The following are the main characteristics of a List: The list is an ordered collection of data
3 min read
Convert Tuple to List in Python
These two Python datatypes can seem to be similar but have different usage in context. The key difference between tuples and lists lies in their mutability. Conversion of the tuple to a list only occurs when you need to modify the element. Example Input: GFG_Tuple = ("DSA, "MERN"," PYTHON", "KOTLIN) Output: GFG_LIST= ["DSA, "MERN"," PYTHON", "KOTLI
3 min read
How toGet First and Last Elements from a Tuple in Python
Tuples are immutable sequences in Python that can store a collection of items. Often, we might need to the retrieve the first and last elements from the tuple. In this article, we'll explore how to achieve this using the various methods in Python. Get First and Last Elements from a Tuple Using IndexingWe can use indexing to access the first and las
2 min read
Python | Count occurrences of an element in a Tuple
In this program, we need to accept a tuple and then find the number of times an item is present in the tuple. This can be done in various ways, but in this article, we will see how this can be done using a simple approach and how inbuilt functions can be used to solve this problem. Examples: Tuple: (10, 8, 5, 2, 10, 15, 10, 8, 5, 8, 8, 2)Input : 4
3 min read
Python | Sort a tuple by its float element
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'),
3 min read
Python | Reversing a Tuple
As we know that in Python, tuples are immutable, thus it cannot be changed or altered. This provides us with limited ways of reversing a tuple, unlike a list. We will go through few techniques on how a tuple in python can be reversed. Examples: Input : tuples = ('z','a','d','f','g','e','e','k') Output : ('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z') Inpu
3 min read
Unpacking a Tuple in Python
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of value
3 min read
Python | Find whether all tuple have same length
Given a list of tuples, the task is to find whether all tuple have same length. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to find whether all # tuple have equal length # Input List initialization Input = [(11, 22, 33), (44, 55, 66)] # printing print("Initial list of tuple", Input) #
6 min read
Python | Remove Consecutive tuple according to key
Sometimes, while working with Python list, we can have a problem in which we can have a list of tuples and we wish to remove them basis of first element of tuple to avoid it's consecutive duplication. Let's discuss certain way in which this problem can be solved. Method : Using groupby() + itemgetter() + next() This task can be performed using comb
5 min read
Evaluate a Hermite series at tuple of points x in Python
In this article, we will be looking toward the approach to evaluating a Hermite series at a tuple of points x in Python and NumPy. Example Tuple: (6,7,8,9,10) Result: [102175. 191631. 329175. 529399. 808815.] Explanation: Hermite series at points x. NumPy.polynomial.hermite.hermval() method To evaluate a Hermite series at a tuple of points x, the u
2 min read
Python | Multiply elements of Tuple
Given, a list of tuples, the task is to multiply the elements of the tuple and return a list of the multiplied elements. Examples: Input: [(2, 3), (4, 5), (6, 7), (2, 8)] Output: [6, 20, 42, 16] Input: [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [242, 1815, 4235, 484] There are multiple ways to multiply the elements of a tuple. Let's see a cou
4 min read
Python | Cumulative Nested Tuple Column Product
Sometimes, while working with records, we can have a problem in which we require to perform index wise multiplication of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using zip() + nested generator expression The
7 min read
Time tuple in Python
Prerequisites: Python datetime module with examples In Python, the datetime module is used to operate with date and time objects. This module has different functions and classes for working with date and time parsing, formatting and arithmetic operations. The datetime module has various constants such as MINYEAR, MAXYEAR etc, various classes like d
3 min read
Evaluate a Hermite_e series at tuple of points x in Python
In this article, we will be looking toward the approach to evaluating a Hermite_e series at a tuple of points x using Python and NumPy. Example: Tuple: (6,7,8,9,10) Result: [102175. 191631. 329175. 529399. 808815.] Explanation: Hermite_e series at points x.NumPy.polynomial.hermite_e.hermeval() method To evaluate a Hermite_e series at a tuple of poi
2 min read
Python | Modify Equal Tuple Rows
Sometimes, while working with Python Records, we can have a problem in which we need to perform the modification of element records on equality of records. This can have a problem in domains that involve data. Let's discuss certain ways in which this task can be performed. Input : test_list = [[(12, 5)], [(13, 2)], [(6, 7)]] test_row = [(13, 2)] Ou
5 min read
Tuple as function arguments in Python
Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different cases can arise. Case 1: fnc(a, b) - Sends a and b
2 min read
Ways to shuffle a Tuple in Python
Shuffling numbers can sometimes prove to be a great help while programming practices. This process can be directly implemented on the data structures which are mutable like lists, but as we know that the tuples are immutable so it cannot be shuffled directly. If you'll try to do so as done in the below code then an error will be raised. Let's see t
2 min read
Python Tuple Exercise
Basic Tuple ProgramsPython program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Sum of tuple elementsPython – Modulo of tuple elementsPython – Row-wise element Addition in Tuple MatrixP
3 min read
Python Tuple Methods
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples. Count() MethodThe count() method of Tuple returns the number of times the given element appears in the tuple. Syntax: tuple.count(
3 min read
Python Tuple - min() Method
While working with tuples many times we need to find the minimum element in the tuple, and for this, we can also use min(). In this article, we will learn about the min() method used for tuples in Python. Syntax of Tuple min() MethodSyntax: min(object) Parameters: object: Any iterable like Tuple, List, etc. Return type: minimum element from the tup
2 min read
How to append elements in Python tuple?
In this article, we will explore how to append elements to a tuple in Python. Appending elements to a tuple in Python may additionally seem counterintuitive due to the immutability of tuples. Understanding TuplesBefore we dive into appending elements to tuples, permit's quick evaluation of what tuples are and why they're beneficial. Tuples are orde
2 min read
Dictionary with Tuple as Key in Python
In Python, dictionaries are versatile data structures that allow you to store and retrieve data efficiently using key-value pairs. While it's common to use simple types like strings or integers as keys, you can also use more complex data structures, such as tuples. In this article, we'll explore five different methods to create and manipulate dicti
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg