Python Tuple vs List - A Quick Comparison Guide

Python Tuple vs. List with our quick guide - a comprehensive comparison to help you choose the right data structure for your coding needs. | ProjectPro

Lists and tuples are both essential built-in data types in Python. Despite their similarities, understanding the differences between them can be challenging for beginners due to their close resemblance. This recipe aims to clarify the fundamental differences between a python tuple and list through examples, helping users comprehend when to opt for tuples over lists.

Feature

Tuple

List

Mutability

Immutable

Mutable

Declaration

Created using parentheses: ( )

Created using square brackets: [ ]

Modifiability

Cannot be modified after creation

Can be modified after creation

Performance

Faster for iteration

Slower for iteration

Memory

Less memory overhead

More memory overhead

Use Cases

Used for fixed, unchangeable data

Used for dynamic data and operations

What is a Python List? 

A Python list is a versatile and dynamic data structure that serves as a collection of elements, allowing for the storage and manipulation of heterogeneous data types within a single container. Lists are mutable, meaning their elements can be modified after the list is created. Elements are accessed by their index, starting from zero. Lists offer functionalities such as appending, removing, and slicing, making them a fundamental tool in Python programming for tasks like storing sequences of values or managing dynamic datasets.

What is a Python Tuple? 

A Python tuple is similar to a list but exhibits immutability, meaning once a tuple is created, its elements cannot be altered. Tuples are defined using parentheses and can contain a mix of data types. They are particularly useful for representing fixed collections of related items, such as coordinates or pairs of values. While tuples lack the flexibility of lists in terms of modification, their immutability makes them suitable for situations where data integrity and consistency are crucial.`

Difference Between List and Tuple in Python with Examples 

The fundamental difference between lists and tuples in Python lies in their mutability; lists are mutable, allowing for modification, while tuples are immutable, ensuring their elements cannot be changed after creation. Now, let's explore the key distinctions between lists and tuples in Python, exploring their differences across various parameters. 

Python List vs Tuple: Syntax 

A list in Python is created using square brackets []. Here's a basic example:

my_list = [1, 2, 3, 'a', 'b', 'c']

A tuple in Python is created using parentheses (). Here's a basic example:

my_tuple = (1, 2, 3, 'a', 'b', 'c') 

Tuple vs List in Python: Mutability 

The most significant distinction between a tuple and a list is that a tuple is immutable, whereas a list is mutable. This means that tuples can't be modified, whereas lists can be changed.

Let us see an example –

Code:

#declaring a list

list_a = [1,2,3]

print("Intial list_a -> ",list_a)

#declaring a tuple

tuple_a = (1,2,3)

print("Initial tuple_a ->", tuple_a)

Python List vs. Tuple: Declaration

Output:

Intial list_a ->  [1, 2, 3]

Initial tuple_a -> (1, 2, 3)

Now, let us try adding another element to our list –

Code:

#trying to modify the list

list_a.append(4)
print("modification 1 -> ", list_a)

#undoing the modification by removing the element

list_a.remove(4)
print("final list -> ", list_a

Tuple vs List Python - Modifiability

Output:

modification 1 ->  [1, 2, 3, 4]

final list ->  [1, 2, 3]

These modifications are not possible while using a tuple. You cannot edit, add, or remove things after they've been created.

But what if you do want to edit a tuple?

You can do so by turning a tuple into a list, editing it, and then turning the list back into a tuple.

Also Check - How to Append the Output of a For Loop in a Python List?

List vs Tuple in Python: Memory Efficiency 

Because lists are mutable, Python allocates an extra memory block in case the list object's size needs to be increased after it is created. Python, on the other hand, allocates only the smallest memory block required for the data because tuples are immutable and constant in size.

Due to this, tuples end up being more efficient in terms of memory than lists.

Let's take a look at this in the code section below –

Code:

#importing required library

import sys

#checking the space occupied by our list and tuple
print("Size of the list",sys.getsizeof(list_a))
print("Size of the tuple", sys.getsizeof(tuple_a)) 

Tuple vs list Python: Memory Efficiency

Output:

Size of the list 80

Size of the tuple 64

We can clearly see that the size of the tuple is smaller than the size of the list even though they are holding the same data at the moment. Due to this, following conclusions can be made - 

List: Lists generally have a slightly larger memory overhead and can be less performant in certain scenarios.

Tuple: Tuples are more memory-efficient and may have better performance in situations where immutability is an advantage.

Additional Differences Between List and Tuple in Python

Some more differences between a tuple and a list are as follows –

  • Tuples are more time-efficient than lists.

  • A list is more convenient for operations like insertion and deletion. Elements can be accessed using the tuples. 

  • There are numerous methods built into lists. There aren't many built-in methods in Tuple.

Python List vs Tuple vs Dictionary vs Set

Check below the comparison table to get an overview of the differences between List, Tuple, Dictionary, and sets. 

Feature 

List 

Tuple 

Dictionary 

Set 

Mutable/ Immutable

Mutable 

Immutable

Mutable 

Mutable 

Syntax 

[element1, element2]

(element1, element2)

{key1: value1, key2: value2}

{element1, element2}

Ordering 

Ordered 

Ordered 

Unordered 

Unordered

Indexing 

Supports indexing

Supports indexing

Uses keys for access

Does not support indexing

Duplicates 

Allows duplicates

Allows duplicates

Values can be duplicated, keys must be unique

Does not allow duplicates

Modifiability 

Can be modified (add, remove, or change elements)

Cannot be modified (immutable)

Can be modified (add, remove, or change key-value pairs)

Can be modified (add or remove elements)

Use Cases 

When the collection of elements may need to be modified during the program

When the collection of elements should remain constant throughout the program

When data needs to be stored and retrieved using keys

When uniqueness of elements is important, and order is not significant

Master Data Science with Python with ProjectPro!

The comparison between Python tuples and lists serves as a foundational understanding for Python developers. Tuples, being immutable, offer advantages in scenarios where data should remain unchanged, while lists, being mutable, provide flexibility for dynamic data manipulation. Choosing the right data structure depends on the specific requirements of a data science project. To truly master Python for data science, practical experience is invaluable. ProjectPro's enterprise-grade projects offer a unique opportunity to apply theoretical knowledge in a hands-on setting. Practicing these projects help beginners gain practical insights, enhance problem-solving skills, and solidify their understanding of Python through a variety of solved project solutions. Explore ProjectPro Repository to get access to over 250+ projects in Data Science, Data Engineering, Machine Learning, Big data. 

FAQs on Python Tuple vs List 

If you have data that isn't designed to be updated in the first place, a tuple should be preferred over a list. However, if there is a chance that the data might increase and shrink throughout the application's runtime, you should use the list data type.

• They're both utilized to store data
• Both are heterogeneous data types, which means they may store any sort of data.
• They're both arranged, which implies that the order in which you placed the things is preserved.
• You can iterate over the items because they are both sequential data types.
• The integer index operator [index] can be used to access items of both lists and tuples.

What Users are saying..

profile image

Ameeruddin Mohammed

ETL (Abintio) developer at IBM
linkedin profile url

I come from a background in Marketing and Analytics and when I developed an interest in Machine Learning algorithms, I did multiple in-class courses from reputed institutions though I got good... Read More

Relevant Projects

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Insurance Pricing Forecast Using XGBoost Regressor
In this project, we are going to talk about insurance forecast by using linear and xgboost regression techniques.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

Time Series Forecasting Project-Building ARIMA Model in Python
Build a time series ARIMA model in Python to forecast the use of arrival rate density to support staffing decisions at call centres.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Learn Object Tracking (SOT, MOT) using OpenCV and Python
Get Started with Object Tracking using OpenCV and Python - Learn to implement Multiple Instance Learning Tracker (MIL) algorithm, Generic Object Tracking Using Regression Networks Tracker (GOTURN) algorithm, Kernelized Correlation Filters Tracker (KCF) algorithm, Tracking, Learning, Detection Tracker (TLD) algorithm for single and multiple object tracking from various video clips.

Skip Gram Model Python Implementation for Word Embeddings
Skip-Gram Model word2vec Example -Learn how to implement the skip gram algorithm in NLP for word embeddings on a set of documents.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

Learn to Build an End-to-End Machine Learning Pipeline - Part 1
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, addressing a major challenge in the logistics industry.