View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Types of Data Structures in Python: List, Tuple, Sets & Dictionary

By Rohit Sharma

Updated on May 23, 2025 | 20 min read | 12.06K+ views

Share:

Did you know that in 2025, Python is the most popular programming language, with a 25.35% rating according to the Tiobe Index? This dominance reflects how the types of data structures in Python enable developers to write high-performance applications across domains like AI and web development.

The types of data structures in Python, list, tuple, set, and dictionary, form the foundation for efficient memory layout, fast lookups, and structured data representation. Each structure differs in mutability, indexing behavior, and internal storage model, such as dynamic arrays or hash tables. 

Choosing the right structure impacts execution time, especially in data-heavy or API-driven workloads. Python simplifies these abstractions, making the types of data structures in Python accessible to both beginners and professionals.

Want to upskill yourself with industry-relevant Python programming skills for efficient software development processes? upGrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!

 

What Are Data Structures in Python?

Python data structures are internal constructs that define how data is allocated, indexed, and accessed in memory. Structures like lists, tuples, sets, and dictionaries are engineered to support efficient operations such as iteration, hashing, and key-based lookups across varied workloads. Understanding the types of data structures in Python is essential for building performant systems, whether you're working with PyTorch data loaders or processing structured HTTP responses

If you want to learn industry-relevant skills to understand different types of data structures in Python, the following courses can help you succeed.

background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months
  • Memory Allocation Models: Python dynamically manages memory. Lists use over-allocation to support amortized O(1) append operations. Tuples, being immutable, are stored in compact memory blocks with fixed length, reducing memory fragmentation and enhancing iteration performance.

Mutability and Hash Integrity: Lists, dictionaries, and sets are mutable, allowing in-place updates. Tuples are immutable and hashable, making them suitable as keys in dictionaries and elements in sets. This distinction is essential for caching, memoization, or key-based object tracking.

  • Indexing and Access Patterns: Lists and tuples provide direct index-based access using zero-based integers, offering O(1) time complexity. Dictionaries and sets rely on hash functions, offering near-constant time complexity for key lookups critical in applications like data serialization and token validation.
  • Framework-Specific Integration
  • list: Frequently used in PyTorch's DataLoader for batching and sampling tensor data.
  • tuple: Commonly used in defining immutable configurations, such as screen coordinates in HTML canvas manipulation.
  • dict: Ideal for parsing and manipulating HTTP headers and JSON responses.
  • set: Efficient for filtering unique values, such as IP addresses or Aadhaar verification logs.
  • Performance Implications: Search operations in a list are O(n), making them unsuitable for large datasets when constant-time lookup is needed. Dictionaries and sets use hash tables, enabling O(1) average-case access. Tuples have slightly better iteration performance than lists due to their immutability and fixed structure.

Code Example:

http_metadata = {
    "Host": "api.irctc.co.in",
    "Content-Type": "application/json",
    "User-Agent": "IRCTCApp/1.0"
}

print("Request content type:", http_metadata["Content-Type"])

 

Output:

Request content type: application/json

Output Explanation:

For example, the dictionary, one of the primary types of data structures in Python, represents metadata in an HTTP request. The dictionary allows constant-time access to headers, which is vital for applications handling RESTful API traffic or secure token verification.

Now, let’s understand what is list data type in Python in details. 

What is a List in Python?

The list data type in Python is an ordered, mutable sequence that allows storing elements of different types, including integers, strings, floats, and booleans, in a single structure. It’s implemented as a dynamic array, supporting rapid index-based access and efficient memory handling. 

Among the types of data structures in Python, lists are widely used in data preprocessing, SQL result parsing, and as intermediaries in TensorFlow pipelines due to their mutability and flexible data handling.

  • Mutability & Dynamic Allocation: Lists can be modified after creation. You can append values, remove items, or overwrite elements at a specific index. This makes them perfect for real-time log updates or handling session state in web applications.
  • Indexing, Slicing & Access Patterns: Lists use zero-based indexing, allowing O(1) access to elements via their index. Python also supports slicing, which lets you extract subsets of the list using start:stop syntax. A feature heavily used in SQL-like data filtering or selecting windows of data for model training.
  • Mixed Data Types & Booleans: Lists support heterogeneous elements. It’s common to store data like [101, "Mumbai", True], where True represents a boolean status for user verification. This makes lists suitable for holding mixed-schema rows fetched from SQL databases or NoSQL document stores.
  • Built-In List Methods: Core methods like .append(), .insert(), .remove(), .sort(), and .reverse() allow for list transformation and restructuring. These are often used in machine learning feature engineering steps or while sanitizing payloads from REST APIs.
  • Integration in Frameworks & APIs: Lists are used in TensorFlow to prepare input arrays before converting them into tensors. In SQL data extraction, fetched results are returned as lists of tuples, highlighting how the list data type in Python fits into predictive analysis operations.

Code Example:

my_list = [10, 3.14, 2, 7, 5, True]  # Includes integer, float, and boolean
my_list.append(8)
my_list.insert(2, 6)
my_list.remove(3.14)
popped_item = my_list.pop(1)

Output:

[True, 10, 8, 7, 6, 5, 2]
Popped item: 6
First item: True
Sliced example: [10, 8]

Output Explanation:

This shows how the list data type in Python can store booleans alongside other data types and supports indexing, slicing, and mutation. Such capabilities make lists ideal for handling complex data records fetched from a MySQL table or feature arrays in AI models.

If you want to learn how AI can help you streamline your software development processes, check out upGrad’s Generative AI Mastery Certificate for Software Development. The program will help you integrate AI solutions and optimize your development workflows for enterprise-grade applications. 

Now, with a clear understanding of tuple data type in Python. Let’s explore list data type in Python which provides an immutable alternative for handling data in Python.

What is a Tuple in Python?

The tuple data type in Python represents an ordered, immutable collection that supports heterogeneous data storage with fixed integrity. Internally, tuples are allocated as contiguous memory blocks, optimized for speed and low overhead. 

Among the core types of data structures in Python, tuples are preferred for storing constants, AWS configuration pairs, or Bootstrap layout breakpoints, where data should remain unchanged throughout execution.

If you're looking to refine your skills and enhance your software engineering expertise, upGrad's Software Engineering course can help you master advanced techniques like Binary Search and more. 

  • Immutability and Performance: Tuples are immutable, meaning no operation can alter their contents once declared. This allows Python to optimize their memory footprint and execution speed. It's commonly used for storing credentials in AWS Lambda functions or static field mappings in a MongoDB schema.
  • Ordered with Index-Based Access: Like lists, tuples maintain order and allow O(1) indexed access. Whether accessing error codes or environment variables by position, this deterministic structure ensures consistency across deployments.
  • Mixed Data Types & Booleans: Tuples can include integers, strings, floats, and booleans in the same container. For example, (200, 'OK', True) could represent an HTTP response code, status, and a boolean for session validity—frequently used in API integrations.
  • Tuple Operations: Although immutable, tuples support operations like slicing, concatenation, repetition, and unpacking. These are especially useful when dealing with multi-section layouts in Bootstrap or passing grouped arguments to machine learning models.
  • Use in Web & Cloud Contexts: In MongoDB, schema-less documents often return field-value mappings temporarily stored in tuples before validation. In AWS DynamoDB, tuples represent key-value pairs in query filters, where immutability ensures safety across concurrent threads.

Code Example:

# Creating a tuple with mixed data types
my_tuple = (10, 'apple', 3.14, True, 'banana')

# Accessing using index
first_item = my_tuple[0]

# Slicing
slice_example = my_tuple[1:3]  # Extracts 'apple' and 3.14

# Concatenation
new_tuple = my_tuple + ('cherry', 'grape')

# Repetition
repeated_tuple = my_tuple * 2

# Output
print(f"First item: {first_item}")
print(f"Sliced: {slice_example}")
print(f"Concatenated: {new_tuple}")
print(f"Repeated: {repeated_tuple}")

Output:

First item: 10
Sliced: ('apple', 3.14)
Concatenated: (10, 'apple', 3.14, True, 'banana', 'cherry', 'grape')
Repeated: (10, 'apple', 3.14, True, 'banana', 10, 'apple', 3.14, True, 'banana')

Output Explanation:

This example illustrates key tuple operations including indexing, slicing, and concatenation. The tuple data type in Python is beneficial in settings where input structures must remain unchanged. Such operations include passing static layout values to a Bootstrap-driven HTML template or locking AWS key sets in a config tuple.

Use Case:
Tuples are frequently used in Indian digital platforms that require immutability in transactional data. For instance, in Aadhaar authentication or UPI callback services, response records such as (status_code, message, is_verified) are stored as tuples to prevent tampering. 

These fixed structures ensure auditability across systems that follow compliance mandates like MeitY guidelines. This reinforces why the types of data in Python, particularly tuples, are trusted in sensitive, state-level applications.

If you want to understand how to differentiate list and tuple types of data structures in Python, check out upGrad’s Learn Basic Python Programming. The 12-hour free certification will help you learn the basics of Python, along with programming and Matplotlib. 

Now, with a clear understanding of the tuple data type in Python. Let’s take a closer look at what a set is in Python with appropriate syntax and use cases. 

What is a Set in Python?

The set data type in Python represents an unordered, mutable collection that enforces uniqueness through a hash-based storage mechanism. Each element must be immutable and hashable, making sets ideal for high-performance operations like deduplication, filtering, and fast membership testing. Among the types of data structures in Python, sets are uniquely suited for applications in JavaScript API token validation and Java-based backend ID filtering. 

Unordered and Hash-Based: Sets are unordered, meaning they do not maintain any insertion sequence, and you cannot access elements using an index. Internally, sets rely on open-addressing hash tables, which provide O(1) average-case time complexity for add, remove, and membership operations.

  • Uniqueness and Deduplication: Sets automatically eliminate duplicates, which is critical when processing webhooks from JavaScript clients or cleaning data pipelines in R. Duplicates skew statistical models. For example, converting a list of product IDs to a set ensures that each ID is counted only once during stock analysis.
  • Mutable Containers, Immutable Elements: Sets are mutable, you can add or remove elements after creation, but the elements themselves must be immutable (e.g., numbers, strings, or tuples). This aligns with the hash function requirements used by the interpreter.
  • Set Algebra and Boolean Logic: Sets support mathematical operations like. .union(), .intersection(), and .difference(),  enabling you to express complex filters or permission checks using logical constructs. These operations are foundational in role-based access control systems written in Java or Python.
  • Application Across Languages and Frameworks
    • JavaScript: Sets store unique DOM event listeners or user session tokens.
    • Java: Set interfaces (HashSet, TreeSet) map closely to Python sets, making cross-language data structures easier to port.
    • R: Data deduplication in datasets can be simulated with Python sets when integrating R scripts with Python in analytics platforms.

Code Example:

# Creating a set with mixed immutable types
my_set = {10, 'apple', 3.14, True, 'banana'}

# Adding and removing elements
my_set.add('cherry')
my_set.remove('apple')
my_set.discard('grape')  # Does not raise an error

# Set algebra
set2 = {20, 'orange', 'banana', 3.14}
union_set = my_set.union(set2)
intersection_set = my_set.intersection(set2)
difference_set = my_set.difference(set2)

# Membership testing
is_banana_in_set = 'banana' in my_set

Output:

Set after operations: {True, 10, 3.14, 'banana', 'cherry'}
Union: {True, 3.14, 10, 'banana', 'orange', 'cherry', 20}
Intersection: {3.14, 'banana'}
Difference: {True, 10, 'cherry'}
'banana' in set?: True

Code Explanation:

This example shows how the set data type in Python allows for fast membership checks, automatic deduplication, and algebraic operations like union and intersection. These features are frequently used in Java or Python-based microservices to filter access scopes and in R to clean categorical survey variables before regression.

Now, let’s explore what are the core characteristics of dictionary in Python. 

What is a Dictionary in Python?

The dictionary data type in Python is an unordered, mutable collection optimized for fast access through unique, immutable keys. It’s backed by a hash table that provides O(1) average time complexity for lookups, insertions, and updates. As one of the core types of data structures in Python, dictionaries are widely used to model JSON-like records ot configuration objects in C#

  • Key-Value Pair Structure: Dictionaries are collections where each key is mapped to a value. This mirrors hash maps in C++ (std::unordered_map) or dictionaries in C#, and is ideal for structured data representations like user profiles or API response mappings.
  • Unordered Yet Predictable (Python 3.7+): While dictionaries are officially unordered, they preserve insertion order from Python 3.7 onward. This makes them useful when rendering styled HTML elements using CSS-like logic or controlling access sequences in event-driven systems.
  • Mutable with Immutable Keys: Dictionaries are mutable; you can update or delete key-value pairs, but their keys must be immutable (e.g., strings, numbers, or tuples). This enables stable hash computation and ensures performance. Storing mutable values like lists or nested dictionaries is supported, but must be handled with care.
  • Instant Access Without Indexing: Dictionaries don’t use a positional index but provide direct access to values via keys. This makes them powerful for storing form-field mappings in web apps or lookup tables in compiled languages like C++ and C#.
  • Serialization Ready: Dictionary structures align naturally with JSON, making them compatible with external APIs or databases. In web frameworks like Flask or Django, dictionaries capture request bodies, route parameters, or return structured responses.

Code Example: 


# Creating a dictionary
person = {'name': 'Jay', 'age': 25, 'city': 'New Delhi'}

# Adding or Updating
person['age'] = 26
person['job'] = 'Engineer'

# Removing elements
removed_value = person.pop('city')
random_item = person.popitem()

# Accessing values
name = person['name']

# Getting keys, values, and items
keys = person.keys()
values = person.values()
items = person.items()

# Output
print(person)
print(f"Removed value: {removed_value}")
print(f"Random item removed: {random_item}")
print(f"Name: {name}")
print(f"Keys: {list(keys)}")
print(f"Values: {list(values)}")
print(f"Items: {list(items)}")

Output:

{'name': 'Jay', 'age': 26}
Removed value: New Delhi
Random item removed: ('job', 'Engineer')
Name: Jay
Keys: ['name', 'age']
Values: ['Jay', 26]
Items: [('name', 'Jay'), ('age', 26)]

Code Explanation:

This demonstrates how the dictionary data type in Python allows you to dynamically add or update records and retrieve keys or values in O(1) time. These structures are particularly effective in environments like CSS-to-JS converters, configuration management in C#, and complex nested form processing in full-stack applications.

Use Case:

In Indian e-Governance systems (like Digilocker or Income Tax portals), citizen metadata is often structured as nested dictionaries. These might store PAN, Aadhaar, or address details as key-value pairs and are serialized for secure API communication. Since these dictionaries may hold both string and numerical keys, they exemplify how versatile the types of data in Python are when dealing with dynamic platforms. 

Also read: Sort Dictionary by Value Python

Now, let’s compare different types of data structures in Python depending on factors like access time, memory usage, and more. 

 

When working with different types of data structures in Python, choosing the right one directly affects performance, readability, and memory usage. Each structure, list, tuple, set, and dictionary has distinct characteristics in terms of mutability, access time, and use case alignment. 

This comparison table shows the differences to help you make informed decisions based on technical needs and workload patterns

Factor List Tuple Set Dictionary
Mutability Mutable (dynamic memory, allows in-place updates) Immutable (static memory, fixed after creation) Mutable (supports in-place addition/removal) Mutable (supports key-value mutations)
Duplicate Storage Supports duplicates (no internal constraints) Supports duplicates (position-based access) Discards duplicates automatically via hashing Values can repeat, keys must be unique and hashable
Order Preservation Maintains insertion order (CPython ≥ 3.7) Maintains insertion order (CPython ≥ 3.7) Unordered (hash-table based, position not guaranteed) Maintains insertion order (CPython ≥ 3.7, not indexable)
Access Time O(1) for index-based retrieva O(1) for index-based retrieval O(1) average for membership check via hashing O(1) for key-based access using hash maps
Memory Usage Higher due to dynamic resizing and metadata Lower due to fixed size and immutability Optimized for uniqueness, compact internal structure Higher due to key hashing and pointer storage
Ease of Use Simple for dynamic, sequential datasets Ideal for fixed, constant reference data Best for fast uniqueness tests, fast lookup Intuitive for mapping identifiers to values
Search Performance O(n) linear search O(n) linear search O(1) on average using hash lookup O(1) key-based lookup via hashing
Common Use Cases Dynamic lists, TensorFlow input batching Constant config, coordinate pairs Filtering duplicates, fast membership in JavaScript APIs API responses, config objects, form field mappings

Also read: Top 25+ Python Projects on GitHub for Every Skill Level: Beginner to Pro

When to Use Each Data Structure?

Selecting the right structure from the available types of data structures in Python depends on the nature of your data, required operations, and performance constraints. Whether you're optimizing read time, enforcing immutability, or managing key-value mappings, each structure brings a specific advantage to different workloads. Understanding these conditions is key to building efficient, scalable, and maintainable Python programs.

  • Use a List: Ideal when order matters and you need to frequently modify the dataset (add, remove, or sort elements). Lists are suitable for batching operations, queuing tasks, or aggregating variable-length results from APIs or SQL queries. Their support for duplicates and positional indexing makes them perfect for sequential data processing in TensorFlow or dynamic table generation in Flask views.
  • Use a Tuple: Choose tuples when your data must remain constant after creation. Tuples are memory-efficient and hashable, allowing them to be used as dictionary keys or elements in sets. They're preferred in configurations, coordinates, or log headers where mutation is not allowed, like storing immutable form metadata in a Django request object.
  • Use a Set: Best suited for operations requiring uniqueness and fast membership checks. Sets eliminate duplicates and offer constant-time lookup, making them effective for deduplicating incoming payloads, user ID validations, or handling tag selections in web forms powered by JavaScript or React.
  • Use a Dictionary: Ideal for structuring data with direct key-based access. Dictionaries are perfect for mapping field names to values in JSON responses, managing user preferences, or constructing localized content blocks for web interfaces. Use them when working with REST APIs, user session tracking, or form-to-database mappings in frameworks like Flask or FastAPI.

Example Scenario:

In a Python-based job portal, applicant resumes are stored as dictionaries (with keys like name, skills, and experience). Each resume’s job history is kept as a list for chronological ordering. Cities applied to are stored in sets to ensure no duplicates in analytics. 

Static fields like country codes or status enums are maintained using tuples for fixed reference. This distribution of the types of data in Python ensures both efficiency and functional clarity across the system.

Also read: Top 10 Python Framework for Web Development

How upGrad Advances Your Expertise in Python Programming?

upGrad offers comprehensive courses that deepen your knowledge of Python, covering everything from basic syntax to advanced topics like algorithms and data structures. With expert mentorship, hands-on projects, and personalized feedback, upGrad ensures you gain practical experience and build real-world applications. 

Here are some of the top courses you can check out: 

Start with upGrad's free courses to build a solid Python foundation, and unlock advanced opportunities in data science and AI.

For personalized career guidance, consult upGrad’s expert counselors or visit our offline centers to find the best course tailored to your goals.

The types of data structures in Python, list, tuple, set, and dictionary, each serve distinct technical purposes based on mutability, indexing, and hashing behavior. Lists are best for dynamic sequences, tuples for fixed immutable data, sets for enforcing uniqueness, and dictionaries for structured key-value mapping. Choose based on required access time, memory constraints, and whether your workload needs constant-time lookup, ordered output, or safe concurrent read operations.

If you are interested in learning fundamentals in Python that can help you deploy scalable projects and applications. These are some of the additional courses that can help you understand Python for enterprise-level applications. 

Curious which courses can help you gain proficiency in Python? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center. 

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Explore our Popular Data Science Courses

Executive Post Graduate Programme in Data Science from IIITB Data Science Bootcamp with AI Master of Science in Data Science from LJMU
Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland Data Science Courses

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Top Data Science Skills to Learn

Data Analysis Course Inferential Statistics Courses
Hypothesis Testing Programs Logistic Regression Courses
Linear Regression Courses Linear Algebra for Analysis

Stay informed and inspired  with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

Read our popular Data Science Articles

Data Science Career Path: A Comprehensive Career Guide Data Science Career Growth: The Future of Work is here Why is Data Science Important? 8 Ways Data Science Brings Value to the Business
Relevance of Data Science for Managers The Ultimate Data Science Cheat Sheet Every Data Scientists Should Have  

 

Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!

Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!

Stay informed and inspired  with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!

References: 
https://content.techgig.com/technology/python-dominates-2025-programming-landscape-with-unprecedented-popularity/articleshow/121134781.cms
 

Frequently Asked Questions

1. Can a list in Python contain another list, tuple, or dictionary?

2. What happens if you use a list as a dictionary key?

3. Are sets suitable for indexing operations in Python?

4. How is tuple memory allocation more efficient than a list?

5. What data structure should I use for storing configuration flags?

6. Can sets be used to remove duplicates from a list?

7. What causes a KeyError in Python dictionaries?

8. Are Python dictionaries thread-safe for read operations?

9. Can tuples be used as elements in a set?

10. Which structure is fastest for membership checks: list, set, or tuple?

11. How do Python data structures impact algorithm design?

Rohit Sharma

763 articles published

Rohit Sharma shares insights, skill building advice, and practical tips tailored for professionals aiming to achieve their career goals.

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

17 Months

upGrad Logo

Certification

3 Months