Data Structures in Python
Introduction
Data structures are a fundamental part of programming because they provide ways to store, organize, and work with information. Whether you are writing a small Python script or developing a larger application, choosing and using an appropriate data structure makes it easier to manage data effectively.
Python provides several built-in data structures that are especially useful for beginners, including lists, tuples, sets, and dictionaries. Each structure has different characteristics and is designed for particular types of data-management tasks. Understanding how these structures work helps you write programs that are easier to organize and maintain.
In this chapter, we will explore commonly used Python data structures, their main characteristics, and basic operations. We will also look at nested data structures, where different structures are combined to represent more detailed information. Finally, coding questions will help you practice the concepts covered in this chapter.
Table of Contents

Lists: The Versatile Container
Lists are among the most flexible and commonly used data structures in Python. A list stores a collection of items in an ordered sequence. The items can have different data types, including integers, strings, and objects.
Lists are mutable, which means their contents can be changed after the list has been created. They also allow duplicate values, making them useful when repeated elements need to be preserved.
Creating a List
A list can be created by placing items inside square brackets:
fruits = ['apple', 'banana', 'cherry']
Each element in a Python list has an index, and indexing starts from 0. Therefore, the first element can be accessed using index 0:
print(fruits[0])
The output is:
apple
Common List Operations
Python provides several operations for adding, removing, and accessing list elements. The append() method adds an item to the end of a list, while insert() places an item at a specific position.
fruits.append('orange')
fruits.insert(1, 'mango')
The remove() method removes an item by its value:
fruits.remove('banana')
List slicing can be used to access a range of elements:
print(fruits[1:3])
Lists are particularly useful when a program needs an ordered collection whose contents may change during execution.
Tuples: Immutable and Efficient
Tuples are similar to lists because they store ordered collections of items. The main difference is that tuples are immutable. Once a tuple has been created, its elements cannot normally be changed.
This characteristic makes tuples useful when information should remain fixed throughout a program. They can be used to represent coordinates, database records, or fixed configuration values.
Creating a Tuple
Tuples are commonly written using parentheses:
coordinates = (10, 20)
Tuple elements can be accessed using their indexes in the same way as list elements:
print(coordinates[0])
The output is:
10
Why Use Tuples?
Tuples are suitable for data that should not change after it has been created. Their immutable nature can help protect fixed information from accidental modification.
Tuples can also be used as dictionary keys when all of their elements are hashable. Lists cannot normally be used as dictionary keys because lists are mutable.
Sets: Unique and Unordered
Sets are collections designed to store unique elements. If duplicate values are supplied, a set keeps only one occurrence of each value. Sets are unordered, so they do not provide a defined index-based sequence for accessing individual elements.
A set can be created using curly braces:
numbers = {1, 2, 3, 4}
It can also be created using the set() function:
numbers = set([1, 2, 3, 4])
Common Set Operations
Python provides methods for adding and removing elements from sets. The add() method adds an item, while remove() removes a specified item.
numbers.add(5)
numbers.remove(3)
Sets also support mathematical operations such as union, intersection, and difference. For example:
odd = {1, 3, 5}
even = {2, 4, 6}
union = odd.union(even)
print(union)
The union combines elements from both sets. Sets are particularly useful when uniqueness is important, such as when duplicate values need to be removed from a collection.
Dictionaries: Key-Value Pairs
Dictionaries store information as key-value pairs. Each key is associated with a value, allowing a program to retrieve information by referring to the corresponding key.
Dictionaries are useful when data needs to be represented through meaningful labels. For example, a student’s information can be stored using keys such as name, age, and courses.
Creating a Dictionary
A dictionary is created using curly braces, with keys and values separated by a colon:
student = {
'name': 'John',
'age': 25,
'courses': ['Math', 'Science']
}
A value can be accessed by using its key:
print(student['name'])
The output is:
John
Common Dictionary Operations
Dictionary values can be added or updated by assigning a value to a key:
student['age'] = 26
An item can be removed using the del statement:
del student['courses']
You can also iterate through dictionary keys and values using the items() method:
for key, value in student.items():
print(f'{key}: {value}')
Dictionaries are useful for storing user information, configuration settings, and other data where values need to be associated with meaningful keys.
Nested Data Structures: Combining the Power
Nested data structures contain one data structure inside another. Python allows lists, tuples, sets, and dictionaries to be combined to represent information with multiple levels of organization.
This approach is useful when simple data structures are not enough to represent relationships between different pieces of information. A nested structure can model data in a hierarchical or multi-level form.
Example: Nested Dictionary
A dictionary can contain other dictionaries and lists as its values:
students = {
'student1': {
'name': 'John',
'age': 25,
'courses': ['Math', 'Science']
},
'student2': {
'name': 'Jane',
'age': 22,
'courses': ['History', 'Literature']
}
}
Nested values can be accessed by following the required keys and indexes:
print(students['student1']['courses'][0])
The output is:
Math
Nested structures are useful when modeling real-world information that has multiple levels. For example, student records can contain personal details and course information, while employee data can contain departments and roles.
Coding Questions
Practice is important when learning data structures. The following questions are designed to help you apply lists, tuples, sets, dictionaries, and nested structures in Python programs.
1. List Manipulation
- Write a function that accepts a list of numbers and returns a new list in which every number is doubled.
- Create a function that accepts two lists and returns only the elements that are common to both lists.
2. Working with Tuples
- Write a function that accepts a list of tuples containing a name and age and returns the names of people who are above 18.
- Create a function that accepts a tuple of numbers and returns a new tuple containing the numbers sorted in ascending order.
3. Set Operations
- Write a function that accepts two sets and returns their symmetric difference, containing elements that are present in either set but not in both.
- Create a function that checks whether one set is a subset of another.
4. Nested Data Structures
- Given a list of dictionaries representing students, with fields such as name, age, and grades, write a function to calculate the average grade of all students.
- Write a function that flattens a list of lists into a single list. For example,
[[1, 2], [3, 4]]should become[1, 2, 3, 4].
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
YT:- DecodeIT
Understanding the Main Data Structures
Although lists, tuples, sets, and dictionaries can all store collections of data, their characteristics are different. Lists are ordered and mutable, which makes them suitable when elements may need to be changed. Tuples are ordered but immutable, making them appropriate for fixed collections.
Sets focus on uniqueness and provide useful set-based operations such as union and intersection. Dictionaries organize information through keys and values, making them useful when data needs to be retrieved using meaningful identifiers.
Understanding these differences helps you work with data more effectively and select the structure that matches the requirements of a particular Python program.
Conclusion
Python’s built-in data structures provide practical ways to store, organize, and manipulate information. Lists are useful for ordered and mutable collections, tuples are suitable for fixed ordered data, sets are designed for unique elements, and dictionaries organize information through key-value relationships.
Nested data structures extend these possibilities by allowing multiple structures to be combined. This makes it possible to represent more detailed information, including hierarchical records and collections containing related data.
By practicing the coding questions in this chapter, learners can gain practical experience with common data-structure operations. As you continue learning Python, becoming comfortable with lists, tuples, sets, dictionaries, and nested structures will provide a strong foundation for working with larger programs and real-world datasets.
Frequently Asked Questions
1. What are data structures in Python?
Data structures are ways of organizing and storing data so that programs can work with information efficiently. Python provides built-in structures such as lists, tuples, sets, and dictionaries.
2. What is a list in Python?
A list is an ordered and mutable collection that can contain different types of values and can also contain duplicate elements.
3. What is a tuple in Python?
A tuple is an ordered collection that is immutable after creation. It is useful for storing information that should remain unchanged.
4. What is a set in Python?
A set is a collection of unique elements. It is useful when duplicate values are not required and when set operations are needed.
5. What is a dictionary in Python?
A dictionary stores information using key-value pairs. Values can be accessed by referring to their associated keys.
6. Why are nested data structures useful?
Nested data structures allow multiple structures to be combined, making them useful for representing hierarchical or multi-level information.
7. Can a list contain different data types?
Yes. A Python list can contain values of different data types, including numbers, strings, objects, and other data structures.
8. Why are sets useful for removing duplicates?
Sets store unique elements, so converting suitable collection data into a set can remove repeated values.
Keywords: Chapter 7 Data Structures in Python, Data Structures in Python, Python data structures, Python lists, Python tuples, Python sets, Python dictionaries, nested data structures in Python, list operations in Python, tuple operations in Python, set operations in Python, dictionary operations in Python, Python data structures notes