Lists and Dictionaries
Lesson Four Structures in Python: Lists and Dictionaries.
Learn Python
February 1, 2025

Lesson Four: Lists and Dictionaries
Welcome to the fourth lesson in our Python learning series! In this lesson, we will focus on two very important structures in Python: Lists and Dictionaries . These structures are used to store data in an organized and easily accessible way, and they are essential in many programming applications.
1. Lists
Lists are one of the most commonly used structures in Python. A list is an ordered collection of elements, and it can contain different types of data (numbers, strings, other lists, etc.).
A. How to Create a List
You can create a list using square brackets []
and separating the elements with commas ,
.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4]
mixed = [1, "apple", 3.14, True]
B. Accessing List Elements
You can access list elements using their index. The index starts at 0
for the first element.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (last element)
C. Modifying List Elements
You can modify the value of a specific element in the list using its index.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Replace "banana" with "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
D. Adding and Removing Elements
- Adding an Element : You can use
append()
to add an element to the end of the list. - Removing an Element : You can use
remove()
orpop()
to delete an element from the list.
fruits = ["apple", "banana", "cherry"]
# Add an element
fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'grape']
# Remove an element
fruits.remove("banana") # Remove "banana"
print(fruits) # Output: ['apple', 'cherry', 'grape']
# Remove the last element
last_fruit = fruits.pop()
print(last_fruit) # Output: grape
print(fruits) # Output: ['apple', 'cherry']
E. Iterating Through a List
You can use a for
loop to iterate through all the elements in the list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
2. Dictionaries
Dictionaries are data structures used to store values as key-value pairs. Each key is associated with a specific value, making data access fast and efficient.
A. How to Create a Dictionary
A dictionary is created using curly braces {}
, where the key and value are separated by a colon :
.
person = {
"name": "Ali",
"age": 25,
"is_student": True
}
B. Accessing Values
You can access values using the key.
person = {
"name": "Ali",
"age": 25,
"is_student": True
}
print(person["name"]) # Output: Ali
print(person["age"]) # Output: 25
C. Modifying and Adding Values
You can modify an existing value or add a new key-value pair.
person = {
"name": "Ali",
"age": 25,
"is_student": True
}
# Modify a value
person["age"] = 30
print(person["age"]) # Output: 30
# Add a new key-value pair
person["city"] = "Riyadh"
print(person) # Output: {'name': 'Ali', 'age': 30, 'is_student': True, 'city': 'Riyadh'}
D. Deleting Elements
You can delete a key-value pair using del
.
person = {
"name": "Ali",
"age": 25,
"is_student": True
}
del person["is_student"]
print(person) # Output: {'name': 'Ali', 'age': 25}
E. Iterating Through a Dictionary
You can iterate through the keys, values, or both using a for
loop.
person = {
"name": "Ali",
"age": 25,
"is_student": True
}
# Iterate through keys
for key in person:
print(key)
# Iterate through values
for value in person.values():
print(value)
# Iterate through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
3. Practical Applications
Application 1: Task Management
tasks = []
def add_task(task):
tasks.append(task)
print(f"Task added: {task}")
def remove_task(task):
if task in tasks:
tasks.remove(task)
print(f"Task removed: {task}")
else:
print("Task not found!")
def show_tasks():
if tasks:
print("Task List:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")
else:
print("No tasks available.")
# Testing the program
add_task("Buy groceries")
add_task("Read a book")
show_tasks()
remove_task("Buy groceries")
show_tasks()
Application 2: Student Data Management
students = {}
def add_student(name, grade):
students[name] = grade
print(f"Student added: {name} - Grade: {grade}")
def get_grade(name):
if name in students:
print(f"Grade for student {name}: {students[name]}")
else:
print("Student not found!")
def show_students():
if students:
print("Student List:")
for name, grade in students.items():
print(f"{name}: {grade}")
else:
print("No students available.")
# Testing the program
add_student("Ali", 90)
add_student("Ahmed", 85)
show_students()
get_grade("Ali")
get_grade("Omar")
4. Tips on Lists and Dictionaries
-
Use Lists when you need ordered elements :
If you want to store a collection of items that need to be ordered or accessed sequentially, lists are the better choice. -
Use Dictionaries for quick access :
If you want to access values based on a specific key (like a student's name), dictionaries are the optimal choice. -
Avoid common mistakes :
When accessing an element in a list or dictionary, make sure it exists first to avoid errors likeIndexError
orKeyError
. Usein
to check for the existence of an element before working with it.
Conclusion
In this lesson, you learned how to use lists and dictionaries in Python. These structures are powerful tools for organizing data and making your code more efficient. Lists are used to store an ordered collection of elements, while dictionaries are used to store data as key-value pairs.
In the next lesson, we will discuss file handling and how to read and write data from files. Keep practicing and don't hesitate to ask questions if you need help!
🚀 You're now on the right path to becoming a professional programmer!
Comments

There are no comments
Please login to leave a review