Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

By Rohit Sharma

Updated on Feb 04, 2025 | 14 min read

Share:

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

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. 

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?

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?

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: 

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!

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!

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?

Rohit Sharma

606 articles published

Get Free Consultation

+91

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

Start Your Career in Data Science Today

Suggested Blogs