- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
- Home
- Blog
- Data Science
- Types of Data Structures in Python: List, Tuple, Sets & Dictionary
Types of Data Structures in Python: List, Tuple, Sets & Dictionary
Updated on Feb 04, 2025 | 14 min read
Share:
Table of Contents
Python provides four key data structures: Lists, Tuples, Sets, and Dictionaries, each optimized for specific use cases. Lists store ordered, mutable collections, while Tuples offer immutable sequences for fixed data. Sets handle unique, unordered elements, useful for removing duplicates, and Dictionaries store key-value pairs for fast lookups.
This guide covers their properties with data structure in Python example. Let’s get started!
What is a List in Python?
A list in Python is a collection of ordered, mutable elements that can store items of any data type, making it a versatile data structure for various applications. It allows for easy manipulation of data, from adding or removing items to sorting or slicing.
Let's take a closer look at the key features that make lists unique and useful in Python:
- Mutable: Lists can be changed after creation, allowing you to add, remove, or modify elements.
- Ordered: The order of elements in a list is preserved, meaning you can access them by their index.
- Can store duplicate values: Unlike sets, lists allow repeated elements, which can be useful in some situations.
- Can store elements of different data types: Lists offer the flexibility to hold integers, strings, booleans, and more, all in one collection.
The syntax for creating a list is simple:
list_name = [element1, element2, element3, ...]
List Operations in Python
With the basic syntax in mind, let's see how you can manipulate lists in Python.
- Adding elements: Use .append() to add an item at the end of the list or .insert() to place it at a specific index.
- Removing elements: Use .remove() to delete an item by its value or .pop() to remove an item by index.
- Indexing and slicing: Access individual elements by their index or extract a portion of the list using slicing.
- Sorting and reversing: Use .sort() to arrange the list in ascending order and .reverse() to reverse the order.
Let’s put everything into practice with an example:
# Creating a list with integers and floats
my_list = [10, 3.14, 2, 7, 5]
# Adding elements
my_list.append(8) # Adding 8 to the end
my_list.insert(2, 6) # Inserting 6 at index 2
# Removing elements
my_list.remove(3.14) # Removing 3.14 from the list
popped_item = my_list.pop(1) # Popping the item at index 1 (6)
# Indexing and Slicing
first_item = my_list[0] # Accessing the first item
slice_example = my_list[1:3] # Slicing the list from index 1 to 2
# Sorting and Reversing
my_list.sort() # Sorting the list
my_list.reverse() # Reversing the list
# Output
print(my_list)
print(f"Popped item: {popped_item}")
print(f"First item: {first_item}")
print(f"Sliced example: {slice_example}")
Output:
my_list = [8, 7, 6, 5, 2, 10]
popped_item = 6
first_item = 8
slice_example = [7, 6]
Explanation:
- Adding elements:
- append(8) adds 8 to the end of the list.
- insert(2, 6) inserts 6 at index 2, shifting other elements.
- Removing elements:
- remove(3.14) removes 3.14 from the list.
- pop(1) removes and returns the item at index 1, which is 6.
- Indexing and Slicing:
- my_list[0] retrieves the first item in the list (8).
- my_list[1:3] returns a new list containing items from index 1 to 2 ([7, 6]).
- Sorting and Reversing:
- sort() arranges the list in ascending order ([2, 5, 6, 7, 8, 10]).
- reverse() reverses the list, producing [10, 8, 7, 6, 5, 2].
Edge Cases to Consider
While lists are quite flexible, there are a few edge cases that might catch you off guard:
- Sorting with Mixed Data Types: Attempting to sort a list with both numbers and strings will result in a TypeError because Python can't compare these two types.
Example:
mixed_list = [3, 'apple', 5]
mixed_list.sort() # This will raise a TypeError
- Removing Non-Existent Elements: Trying to remove an element that doesn't exist in the list will raise a ValueError.
Example:
my_list = [1, 2, 3]
my_list.remove(4) # This will raise a ValueError
Also Read: Python Program to Convert List to String
Now that you've mastered lists, let’s dive into tuples, which provide an immutable alternative for handling data in Python.
What is a Tuple in Python?
A tuple in Python is an ordered, immutable collection of elements, which makes it useful when you need to ensure the integrity of your data. Unlike lists, once a tuple is created, it cannot be modified, which is ideal for storing constant data.
Let’s dive into the key features that make tuples distinct and beneficial in Python:
- Immutable: Once created, tuples cannot be altered (no adding, removing, or modifying elements).
- Ordered: Tuples maintain the order of elements, so you can access them by their index.
- Can store duplicate values: Like lists, tuples can have repeated elements.
- Can store elements of different data types: Tuples can hold integers, strings, booleans, and more in one collection.
The syntax for creating a tuple is:
tuple_name = (element1, element2, element3, ...)
Tuple Operations in Python
Let’s explore some common operations and manipulations you can perform on tuples.
- Accessing elements: Use indexing to access individual elements by their position.
- Slicing: You can slice a tuple to get a portion of the elements.
- Concatenation: Combine multiple tuples into one. These are useful when you need to create a new tuple without modifying the original.
- Repetition: Repeat a tuple using the multiplication operator *.
Let’s apply these operations in an example:
# Creating a tuple with mixed data types
my_tuple = (10, 'apple', 3.14, True, 'banana')
# Accessing elements
first_item = my_tuple[0] # Accessing the first item
# Slicing
slice_example = my_tuple[1:3] # Slicing the tuple from index 1 to 2
# Concatenation
new_tuple = my_tuple + ('cherry', 'grape') # Concatenating another tuple
# Repetition
repeated_tuple = my_tuple * 2 # Repeating the tuple
Output:
first_item = 10
slice_example = ['apple', 3.14]
new_tuple = (10, 'apple', 3.14, True, 'banana', 'cherry', 'grape')
repeated_tuple = (10, 'apple', 3.14, True, 'banana', 10, 'apple', 3.14, True, 'banana')
Explanation:
- Accessing elements:
- my_tuple[0] retrieves the first item in the tuple (10).
- Slicing:
- my_tuple[1:3] returns a new tuple containing items from index 1 to 2 (['apple', 3.14]).
- Concatenation:
- my_tuple + ('cherry', 'grape') combines the original tuple with a new one containing "cherry" and "grape".
- Repetition:
- my_tuple * 2 creates a new tuple that repeats the original tuple twice.
Edge Cases to Consider
While tuples are very efficient, there are a few edge cases to keep in mind:
- Attempting to Modify a Tuple: Trying to modify an element of a tuple will raise a TypeError since tuples are immutable.
Example:
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # This will raise a TypeError
- Index Out of Range: Accessing an index that doesn’t exist in the tuple will raise an IndexError.
Example:
my_tuple = (1, 2, 3)
my_tuple[5] # This will raise an IndexError
Also Read: List vs Tuple: Understanding the Differences in Python
Now that you understand the immutability and benefits of tuples, let’s move on to explore sets, another versatile data structure in Python.
What is a Set in Python?
A set in Python is an unordered collection of unique elements, making it ideal for operations where the uniqueness of items is essential. Sets are mutable, meaning you can add and remove elements, but unlike lists, they don’t store duplicates. Sets use hash tables to store unique values. If you add a duplicate, it is automatically discarded.
Let’s explore the key features that define sets in Python:
- Unordered: Sets do not maintain the order of elements, meaning you cannot access elements by their index.
- Unique elements: Sets automatically remove duplicate values, ensuring that each element appears only once.
- Mutable: You can add or remove elements after the set is created.
- Can store elements of different data types: While sets can store elements of various types, all elements must be immutable (e.g., numbers, strings, and tuples).
The syntax for creating a set is simple:
set_name = {element1, element2, element3, ...}
Set Operations in Python
Now that you know the basic syntax of sets, let’s take a closer look at common operations you can perform on sets.
- Adding elements: Use .add() to add a single element to a set.
- Removing elements: Use .remove() to delete an element by value, or .discard() to remove an element without raising an error if the element doesn’t exist.
- Set union, intersection, and difference: Use .union(), .intersection(), and .difference() to perform mathematical set operations.
- Set membership: Use the in keyword to check if an element exists in the set.
Let’s dive into an example to see these operations in action:
# Creating a set with mixed data types
my_set = {10, 'apple', 3.14, True, 'banana'}
# Adding elements
my_set.add('cherry') # Adding 'cherry' to the set
# Removing elements
my_set.remove('apple') # Removing 'apple' from the set
my_set.discard('grape') # Discarding 'grape' (no error even though 'grape' is not in the set)
# Set operations
set2 = {20, 'orange', 'banana', 3.14}
union_set = my_set.union(set2) # Union of my_set and set2
intersection_set = my_set.intersection(set2) # Intersection of my_set and set2
difference_set = my_set.difference(set2) # Difference between my_set and set2
# Set membership
is_banana_in_set = 'banana' in my_set # Checking if 'banana' is in the set
Output:
my_set = {True, 10, 3.14, 'banana', 'cherry'}
union_set = {True, 10, 3.14, 'apple', 'banana', 'cherry', 20, 'orange'}
intersection_set = {3.14, 'banana'}
difference_set = {True, 10, 'cherry'}
is_banana_in_set = True
Explanation:
- Adding elements:
- add('cherry') adds "cherry" to the set. Sets only store unique elements, so if you try to add "cherry" again, it won't be added.
- Removing elements:
- remove('apple') removes "apple" from the set.
- discard('grape') does not raise an error even though "grape" is not in the set.
- Set operations:
- union() combines all elements from both sets and removes duplicates.
- intersection() returns elements that are present in both sets.
- difference() returns elements that are in the first set but not in the second.
- Set membership:
- 'banana' in my_set returns True because "banana" is indeed in the set.
Edge Cases to Consider
While sets are a powerful tool in Python, there are some important edge cases to keep in mind:
- Unordered nature: Since sets do not maintain order, you cannot access elements using indices or guarantee the order in which they are stored.
Example:
my_set = {1, 2, 3}
print(my_set[0]) # This will raise a TypeError
- Mutability of sets: While sets are mutable, the elements inside a set must be immutable. You cannot store lists or dictionaries inside a set.
Example:
my_set = {[1, 2], 'apple'} # This will raise a TypeError
- Attempting to add duplicates: Sets automatically discard duplicates, so adding a duplicate element will have no effect.
Example:
my_set = {1, 2, 3}
my_set.add(2) # The set remains {1, 2, 3}
Also Read: What is Mutable and Immutable in Python? Definitions, Data Types, Examples, and Key Differences
Now that you understand how sets work, let’s explore dictionaries, another powerful data structure in Python.
upGrad’s Exclusive Data Science Webinar for you –
Transformation & Opportunities in Analytics & Insights
What is a Dictionary in Python?
A dictionary in Python is an unordered collection of key-value pairs, each key unique. It is a highly efficient data structure that allows for fast lookups, inserts, and updates. The keys in a dictionary act like indexes, while the values hold the corresponding data.
Let’s break down the key features of dictionaries:
- Unordered: Dictionaries do not maintain the order of elements. However, starting from Python 3.7, dictionaries are insertion-ordered, meaning they preserve the order in which items are added (though this is not the primary purpose).
- Key-Value Pairs: Each item in the dictionary is a pair consisting of a unique key and its associated value.
- Mutable: You can change the contents of a dictionary by adding, removing, or updating key-value pairs.
- Keys are immutable: Dictionary keys must be of an immutable data type, such as strings, numbers, or tuples.
The syntax for creating a dictionary is simple:
dict_name = {key1: value1, key2: value2, ...}
Dictionary Operations in Python
Now that you know the basic structure of a dictionary, let's explore some of the common operations you can perform on dictionaries.
- Adding or Updating elements: Use the assignment operator to add new key-value pairs or update existing ones.
- Removing elements: Use .pop() to remove an element by key or .popitem() to remove and return a random key-value pair.
- Accessing values: You can access values by referring to their keys.
- Keys, values, and items: Use .keys(), .values(), and .items() to get the keys, values, or both as pairs from the dictionary.
Dictionaries use hash tables to map keys to values, making lookups nearly instant (O(1) complexity). However, this also means keys must be immutable (e.g., strings, numbers, or tuples)
Let’s see these operations in action with an example:
# Creating a dictionary
person = {'name': 'Jay', 'age': 25, 'city': 'New Delhi'}
# Adding or Updating elements
person['age'] = 26 # Updating the age
person['job'] = 'Engineer' # Adding a new key-value pair
# Removing elements
removed_value = person.pop('city') # Removing the key 'city'
random_item = person.popitem() # Removing and returning a random key-value pair
# Accessing values
name = person['name'] # Accessing the value associated with the key 'name'
# Keys, values, and items
keys = person.keys() # Getting all keys
values = person.values() # Getting all values
items = person.items() # Getting all key-value pairs
Output:
person = {'name': 'Jay', 'age': 26, 'job': 'Engineer'}
removed_value = 'New Delhi'
random_item = ('job', 'Engineer')
name = 'Jay'
keys = dict_keys(['name', 'age', 'job'])
values = dict_values(['John', 26, 'Engineer'])
items = dict_items([('name', 'Jay'), ('age', 26), ('job', 'Engineer')])
Explanation:
- Adding or Updating elements:
- person['age'] = 26 updates the value associated with the key 'age'.
- person['job'] = 'Engineer' adds a new key-value pair to the dictionary.
- Removing elements:
- pop('city') removes and returns the value associated with the key 'city'.
- popitem() removes and returns a random key-value pair from the dictionary.
- Accessing values:
- person['name'] retrieves the value associated with the key 'name' (in this case, 'John').
- Keys, values, and items:
- person.keys() returns a view of all the keys in the dictionary.
- person.values() returns a view of all the values in the dictionary.
- person.items() returns a view of all key-value pairs in the dictionary.
Edge Cases to Consider
While dictionaries are very useful, there are some important edge cases to keep in mind:
- KeyError: If you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised.
Example:
person = {'name': 'Jay', 'age': 26}
print(person['address']) # This will raise a KeyError
- Mutable Values: You can store mutable objects (like lists or dictionaries) as values in a dictionary. However, be cautious when modifying mutable values, as this may affect your data unintentionally.
Example:
person = {'name': 'Jay', 'hobbies': ['reading', 'swimming']}
person['hobbies'].append('coding') # This modifies the list directly
- Overwriting Values: If you assign a new value to an existing key, it will overwrite the previous value associated with that key.
Example:
person = {'name': 'Jay', 'age': 25}
person['age'] = 26 # This overwrites the value of 'age'
Also Read: A Complete Python Cheat Sheet (Updated 2024)
Next, let’s break down these types of data structures in Python across several factors, helping you choose the right one based on your specific use case.
Comparison of Data Structures in Python
When working with data in Python, understanding the strengths and weaknesses of each data structure can significantly impact the efficiency and clarity of your code.
Let’s compare the types of data structures in Python based on the following factors:
Factor |
List |
Tuple |
Set |
Dictionary |
Mutability | Mutable (can be modified) | Immutable (cannot be modified) | Mutable (can be modified) | Mutable (can be modified) |
Storage of Duplicate Values | Can store duplicates | Can store duplicates | Does not allow duplicates | Can store duplicates in values, not keys |
Order Preservation | Ordered (from Python 3.7 onwards) | Ordered (from Python 3.7 onwards) | Unordered | Ordered (from Python 3.7 onwards) |
Access Time | O(1) for indexing | O(1) for indexing | O(1) for membership test (in) | O(1) for key lookup |
Memory Usage | Higher memory usage | Lower memory usage | Memory-efficient due to unique elements | Higher memory usage due to key-value pairs |
Ease of Use | Easy to use for simple tasks | Easy for fixed collections | Ideal for uniqueness checks | Ideal for mapping data, easy key-value access |
Search Performance | O(n) | O(n) | O(1) (average for lookups) | O(1) for key lookup |
Common Use Cases | Storing ordered, mutable collections | Storing immutable, ordered data | Ensuring uniqueness in collections | Storing key-value pairs, fast lookups |
To further enhance your Python skills, upGrad offers tailored programs designed to take your expertise to the next level.
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:
- Learn Python Libraries: NumPy, Matplotlib & Pandas
- Executive PG Diploma in Data Science & AI
- Post Graduate Certificate in Data Science & AI (Executive)
- Executive Diploma in Machine Learning and AI by IIIT Bangalore
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.
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
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
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
Frequently Asked Questions
1. What are the types of data structures in Python?
2. How do I choose between a list and a tuple in Python?
3. Can a set store duplicate values?
4. How do you access elements in a Python list?
5. How do Python dictionaries handle collisions in hashing?
6. When should I use a tuple instead of a list?
7. What is the significance of immutability in a tuple?
8. Why are sets faster for lookups than lists?
9. How do sets handle ordering?
10. How do I loop through a dictionary in Python?
11. Can I use a list of lists in Python?
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources