Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Create list of tuples using for loop
Next article icon

Memory Management in Lists and Tuples using Python

Last Updated : 20 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, lists and tuples are common data structures used to store sequences of elements. However, they differ significantly in terms of memory management, mutability, and performance characteristics.

Table of Content

  • Memory Allocation in Lists
  • Memory Allocation in Tuples
  • Comparison of Lists and Tuples in Terms of Memory Usage

This article will explore How Memory Management works in Lists and Tuples using Python.

Memory Allocation in Lists

Lists in Python are mutable sequences which means their elements can be modified after the list is created. Due to this mutability, lists in Python have some additional overhead.

  • Dynamic Size: The memory for a list can grow or shrink as elements are added or removed.
  • Overhead: Python lists are implemented as arrays of pointers to objects and thus they consume more memory compared to other simpler data structures like arrays.
  • Internal Representation: Lists use a concept called over-allocation. When a list is created or extended, Python allocates more memory than is needed for the current elements. This minimizes the need for frequent resizing during list growth which improves performance but uses more memory.
list
Memory Management in Lists
  • Lists, unlike tuples, are mutable. To accommodate future additions, Python pre-allocates extra memory beyond the current size of the list.
  • When the list is initialized, Python allocates additional empty slots in memory (e.g., 4 slots in this case). This allocation is beyond the size of the current elements, ensuring efficient resizing for subsequent additions.
  • This extra allocation avoids the need to reallocate memory every time a new element is added. When the new element 'now' is added, it is inserted into one of the pre-allocated empty slots.
  • The list now has 5 elements. This demonstrates the dynamic resizing capability of lists and how Python optimizes memory usage by reserving space for potential future growth.

Example:

Python
import sys  a = ['Learn', 'Python', 'with', 'GFG', 'now']  # Checking memory usage of the list print("Memory size of list:", sys.getsizeof(a))  # Returns the size in bytes 

Output
Memory size of list: 112 

Memory Allocation in Tuples

Tuples, unlike lists are immutable, meaning their contents cannot be changed once they are created. This immutability provides certain optimizations in terms of memory management.

  • Fixed Size: Once a tuple is created, its size is fixed which means no resizing is required.
  • Lower Memory Overhead: Since tuples are immutable, Python can allocate memory more efficiently.
  • Memory Efficiency: Tuples are more memory efficient when dealing with a large amount of data that doesn't require modification. The reduced overhead makes tuples faster in terms of memory access and iteration.
tuples
Memory Management in Tuple
  • Memory allocated for the tuple corresponds exactly to its size (4 elements). No extra memory is allocated for future growth because tuples are immutable.
  • When a new element ('now') is added, a new tuple (Tnew) is created in memory. This tuple contains all the elements from the old tuple (T1) plus the new element. The original tuple (T1) remains unchanged.
  • This process demonstrates that tuples require new memory allocation whenever their size changes.

Example:

Python
import sys a = ('Learn', 'Python', 'with', 'GFG')  # Checking memory usage of the tuple print("Memory size of tuple:", sys.getsizeof(a))  # Returns the size in bytes 

Output
Memory size of tuple: 88 

Comparison of Lists and Tuples in Terms of Memory Usage

When it comes to memory usage tuples are more efficient than lists due to their immutability. Lists being mutable require extra space to handle dynamic resizing and other internal operations.

Feature

List

Tuple

Mutability

Mutable(can be modified)

Immutable(cannot be modified)

Memory Overhead

Higher(due to dynamic resizing)

Lower(fixed size)

Performance

Slower(due to resizing & mutability)

Faster(due to immutability)

Use case

Used when elements change frequently

Used when elements are fixed


Next Article
Python - Create list of tuples using for loop

S

sourabhsahu22
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
  • python-tuple
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python | Find number of lists in a tuple
    Given a tuple of lists, the task is to find number of lists in a tuple. This is a very basic problem but can be useful while making some utility application. Method #1: Using len C/C++ Code # Python code to find number of list in a tuple # Initial list Input1 = ([1, 2, 3, 4], [5, 6, 7, 8]) Input2 =
    4 min read
  • Python - Create list of tuples using for loop
    In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
    2 min read
  • Unzip List of Tuples in Python
    The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for
    2 min read
  • Merge Two Lists into List of Tuples - Python
    The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
    3 min read
  • Find Largest Item in a Tuple - Python
    We need to find the largest number or the top N largest numbers from a tuple. For Example: Input: (10,20,23,5,2,90) #tupleOutput: 90Explanation: 90 is the largest element from tuple There are several efficient ways to achieve this: Using max()max() in Python is the most efficient way to find the lar
    4 min read
  • Python - Minimum in tuple list value
    Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Let’s discuss certai
    5 min read
  • Print a List of Tuples in Python
    The task of printing a list of tuples in Python involves displaying the elements of a list where each item is a tuple. A tuple is an ordered collection of elements enclosed in parentheses ( ), while a list is an ordered collection enclosed in square brackets [ ]. Using print()print() function is the
    2 min read
  • Python | Count tuples occurrence in list of tuples
    Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using It
    5 min read
  • Python | Pair and combine nested list to tuple list
    Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the
    10 min read
  • Python | Combining tuples in list of tuples
    Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences