Types of Data Structures in Python: List, Tuple, Sets & Dictionary
By Rohit Sharma
Updated on Feb 04, 2025 | 14 min read | 11.8k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Feb 04, 2025 | 14 min read | 11.8k views
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!
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:
The syntax for creating a list is simple:
list_name = [element1, element2, element3, ...]
With the basic syntax in mind, let's see how you can manipulate lists in Python.
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:
While lists are quite flexible, there are a few edge cases that might catch you off guard:
Example:
mixed_list = [3, 'apple', 5]
mixed_list.sort() # This will raise a TypeError
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.
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:
The syntax for creating a tuple is:
tuple_name = (element1, element2, element3, ...)
Let’s explore some common operations and manipulations you can perform on tuples.
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:
While tuples are very efficient, there are a few edge cases to keep in mind:
Example:
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # This will raise a TypeError
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.
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:
The syntax for creating a set is simple:
set_name = {element1, element2, element3, ...}
Now that you know the basic syntax of sets, let’s take a closer look at common operations you can perform on sets.
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:
While sets are a powerful tool in Python, there are some important edge cases to keep in mind:
Example:
my_set = {1, 2, 3}
print(my_set[0]) # This will raise a TypeError
Example:
my_set = {[1, 2], 'apple'} # This will raise a TypeError
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
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:
The syntax for creating a dictionary is simple:
dict_name = {key1: value1, key2: value2, ...}
Now that you know the basic structure of a dictionary, let's explore some of the common operations you can perform on dictionaries.
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:
While dictionaries are very useful, there are some important edge cases to keep in mind:
Example:
person = {'name': 'Jay', 'age': 26}
print(person['address']) # This will raise a KeyError
Example:
person = {'name': 'Jay', 'hobbies': ['reading', 'swimming']}
person['hobbies'].append('coding') # This modifies the list directly
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.
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.
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!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources