Section 3: Data Structures in Python
In this section, we'll explore various essential data structures in Python, including lists, tuples,
sets, and dictionaries. We'll learn about their properties, use cases, and manipulation
techniques.
3.1 Lists
A list is a versatile data structure that can hold an ordered collection of items. It's mutable,
meaning you can add, modify, and remove items from it.
Properties and Usage:
● Lists are enclosed in square brackets [ ].
● Elements are separated by commas.
● Lists can contain elements of different types.
● Lists are indexed, meaning you can access elements by their position.
● Lists are mutable, so you can change their content.
Example:
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing list elements
print(fruits[0]) # Output: apple
# Modifying a list element
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
3..1.1 List Slicing
List slicing allows you to extract a portion of a list by specifying a range of indices. The syntax
for list slicing is [start:end], where start is the index of the first element to include, and end is
theindex of the first element to exclude.
Example:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slicing a list
subset = numbers[2:6] # [2, 3, 4, 5]
List Slicing with Step
You can also include a step value to skip elements while slicing. The syntax for this is
[start:end:step].
Example:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slicing with a step
subset = numbers[1:9:2] # [1, 3, 5, 7]
Common List Methods
Here are some frequently used list methods that help manipulate lists:
append(): Adds an element to the end of the list.
fruits = ["apple", "banana"]
fruits.append("orange")
# fruits = ["apple", "banana", "orange"]
insert(): Inserts an element at a specified index.
numbers = [1, 2, 3]
numbers.insert(1, 4)
# numbers = [1, 4, 2, 3]
remove(): Removes the first occurrence of a specified element.
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
# fruits = ["apple", "orange"]
pop(): Removes and returns an element from a specified index (default is the last index).
numbers = [1, 2, 3]
popped = numbers.pop(1)
# numbers = [1, 3], popped = 2
index(): Returns the index of the first occurrence of a specified element.
fruits = ["apple", "banana", "orange"]
index = fruits.index("banana")
# index = 1
sort(): Sorts the list in ascending order.
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
# numbers = [1, 1, 2, 3, 4, 5, 9]
reverse(): Reverses the order of the list.
numbers = [1, 2, 3, 4]
numbers.reverse()
# numbers = [4, 3, 2, 1]
Practice Exercises:
Exercise 1: List Slicing
Create a list of numbers from 0 to 9.
Use slicing to extract a subset of even numbers.
Exercise 2: List Methods
❖ Create a list of colors.
❖ Append a new color to the list.
❖ Insert a color at the second position.
❖ Remove a color from the list.
❖ Print the index of a specific color.
❖ Sort the list of colors in alphabetical order.
Exercise 3 List Operations
❖ Create a list of your favorite movies.
❖ Add a new movie to the list.
❖ Replace the second movie with a different movie.
❖ Print the length of the list.
Exercise 4: List Slicing
❖ Create a list of numbers from 1 to 10.
❖ Print the elements from the 3rd to the 7th position.
3.2 Tuples
A tuple is similar to a list but is immutable, meaning its elements cannot be changed once
defined.
Properties and Usage:
● Tuples are enclosed in parentheses ( ).
● Elements are separated by commas.
● Tuples can contain elements of different types.
● Tuples are indexed, like lists.
● Tuples are immutable.
Example:
# Creating a tuple
point = (3, 4)
# Accessing tuple elements
x = point[0] # x = 3
# Tuple unpacking
x, y = point # x = 3, y = 4
Tuple Methods:
count(): Returns the number of occurrences of a specified value in the tuple.
fruits = ("apple", "banana", "apple", "orange")
count = fruits.count("apple")
# count = 2
index(): Returns the index of the first occurrence of a specified value in the tuple.
fruits = ("apple", "banana", "orange")
index = fruits.index("banana")
# index = 1
len(): Returns the number of elements in the tuple.
fruits = ("apple", "banana", "orange")
length = len(fruits)
# length = 3
Practice Exercises:
Exercise 1: Tuple Methods
❖ Create a tuple of numbers with some duplicates.
❖ Use the count() method to find the number of occurrences of a specific number.
❖ Use the index() method to find the index of another number.
❖ Calculate the length of the tuple using the len() method.
Exercise 2: Tuple Creation
Create a tuple of days in a week.
Access the third day from the tuple.
Exercise 3: Tuple Unpacking
Create a tuple with your name and age.
Unpack the tuple into separate variables.
3.3 Sets
A set is an unordered collection of unique elements. It's useful for tasks like eliminating
duplicate values and checking membership.
Properties and Usage:
● Sets are enclosed in curly braces { }.
● Elements are separated by commas.
● Sets can't contain duplicate elements.
● Sets are not indexed.
Example:
# Creating a set
colors = {"red", "green", "blue"}
# Adding an element to a set
colors.add("yellow")
# Removing an element from a set
colors.remove("red")
Set Methods:
add(): Adds an element to the set.
fruits = {"apple", "banana"}
fruits.add("orange")
# fruits = {"apple", "banana", "orange"}
remove(): Removes the specified element from the set. Raises an error if the element is
not present.
fruits = {"apple", "banana", "orange"}
fruits.remove("banana")
# fruits = {"apple", "orange"}
discard(): Removes the specified element from the set. Does nothing if the element is
not present.
fruits = {"apple", "banana", "orange"}
fruits.discard("banana")
# fruits = {"apple", "orange"}
pop(): Removes and returns an arbitrary element from the set. Raises an error if the set
is empty.
fruits = {"apple", "banana", "orange"}
removed_fruit = fruits.pop()
# removed_fruit is an arbitrary element from the set
clear(): Removes all elements from the set, making it empty.
fruits = {"apple", "banana", "orange"}
fruits.clear()
# fruits = set()
union(): Returns a new set containing all elements from both sets (without duplicates).
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# union_set = {1, 2, 3, 4, 5}
intersection(): Returns a new set containing common elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# intersection_set = {3}
difference(): Returns a new set containing elements present in the first set but not in the
second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
# difference_set = {1, 2}
symmetric_difference(): Returns a new set containing elements present in either of the
sets, but not in both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
# symmetric_difference_set = {1, 2, 4, 5}
Practice Exercises:
Exercise 1: Set Methods
❖ Create a set of your favorite animals.
❖ Use the add() method to add a new animal to the set.
❖ Use the remove() method to remove an animal from the set.
❖ Use the union() method to combine two sets of animals.
❖ Use the intersection() method to find common animals between two sets.
❖ Use the difference() method to find animals unique to the first set.
Exercise 2: Set Operations
❖ Create a set of your favorite books.
❖ Add a new book to the set.
❖ Remove a book from the set.
Exercise 3.3.2: Set Membership
❖ Create a set of programming languages.
❖ Check if "Python" is in the set.
3.4 Dictionaries
A dictionary is a collection of key-value pairs, where each key maps to a value. It's useful for
storing and retrieving data with named keys.
Properties and Usage:
● Dictionaries are enclosed in curly braces { }.
● Key-value pairs are separated by colons :.
● Keys must be unique and immutable (strings, numbers, tuples).
● Dictionaries are not ordered.
Example:
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
# Accessing dictionary values
print(person["name"]) # Output: Alice
Dictionary Methods:
keys(): Returns a list of all the keys in the dictionary.
person = {"name": "Alice", "age": 30, "city": "New York"}
keys = person.keys()
# keys = ["name", "age", "city"]
values(): Returns a list of all the values in the dictionary.
person = {"name": "Alice", "age": 30, "city": "New York"}
values = person.values()
# values = ["Alice", 30, "New York"]
items(): Returns a list of tuples, where each tuple contains a key-value pair.
person = {"name": "Alice", "age": 30, "city": "New York"}
items = person.items()
# items = [("name", "Alice"), ("age", 30), ("city", "New York")]
get(): Returns the value for a specified key. If the key is not found, it returns a default
value.
person = {"name": "Alice", "age": 30}
name = person.get("name", "Unknown")
# name = "Alice"
occupation = person.get("occupation", "Unknown")
# occupation = "Unknown"
pop(): Removes and returns the value for a specified key. Raises an error if the key is
not found.
person = {"name": "Alice", "age": 30}
name = person.pop("name")
# name = "Alice", person = {"age": 30}
popitem(): Removes and returns the last key-value pair as a tuple. Raises an error if the
dictionary is empty.
person = {"name": "Alice", "age": 30}
last_item = person.popitem()
# last_item = ("age", 30), person = {"name": "Alice"}
clear(): Removes all key-value pairs from the dictionary, making it empty.
person = {"name": "Alice", "age": 30}
person.clear()
# person = {}
update(): Updates the dictionary with key-value pairs from another dictionary or
iterable.
person = {"name": "Alice", "age": 30}
new_data = {"city": "New York", "occupation": "Engineer"}
person.update(new_data)
# person = {"name": "Alice", "age": 30, "city": "New York", "occupation": "Engineer"}
Practice Exercises:
Exercise 1: Dictionary Methods
❖ Create a dictionary of student names and their corresponding ages.
❖ Use the keys() method to get a list of all student names.
❖ Use the values() method to get a list of all student ages.
❖ Use the items() method to get a list of tuples containing name-age pairs.
❖ Use the get() method to retrieve the age of a specific student.
❖ Use the pop() method to remove a student from the dictionary.
Exercise 2: Dictionary Operations
Create a dictionary of your favorite foods with their ratings.
Add a new food and rating to the dictionary.
Modify the rating of an existing food.
Exercise 3: Dictionary Access
Create a dictionary of country codes and their corresponding countries.
Print the country name for a given country code.
3.5 Lists vs. Tuples vs. Sets vs. Dictionaries
Comparing the characteristics and use cases of these four data structures.
In this section, we'll compare the characteristics, use cases, and scenarios where each of these
four data structures—lists, tuples, sets, and dictionaries—shines.
3.5.1 Lists
Characteristics:
● Ordered collection of items.
● Elements are enclosed in square brackets [ ].
● Mutable: You can modify, add, and remove elements.
● Elements can be of any data type.
Use Cases:
● When you need to store and manipulate a collection of items with a specific order.
● Lists are commonly used for tasks like managing to-do lists, collecting user inputs, and
more.
Scenarios:
Storing a list of user names.
Managing a playlist of songs in a specific order.
Tracking the history of actions in a program.
3.5.2 Tuples
Characteristics:
● Ordered collection of items.
● Elements are enclosed in parentheses ( ).
● Immutable: Once defined, elements cannot be changed.
● Elements can be of any data type.
Use Cases:
● When you want to represent a fixed collection of related values.
● Tuples are often used to return multiple values from functions or as keys in dictionaries.
Scenarios:
Storing latitude and longitude coordinates of locations.
Representing RGB color values.
Returning multiple values from a function, like coordinates or details.
3.5.3 Sets
Characteristics:
● Unordered collection of unique items.
● Elements are enclosed in curly braces { }.
● Mutable: You can add and remove elements, but not modify them.
● Elements must be hashable (immutable data types).
Use Cases:
● When you need to eliminate duplicate values from a collection.
● Sets are useful for membership testing and finding common elements between
collections.
Scenarios:
Keeping track of unique user IDs in an online forum.
Finding common interests between two groups of users.
Eliminating duplicate items from a list.
3.5.4 Dictionaries
Characteristics:
● Unordered collection of key-value pairs.
● Elements are enclosed in curly braces { }.
● Mutable: You can modify, add, and remove key-value pairs.
● Keys must be unique and immutable.
Use Cases:
● When you need to associate values with specific keys for efficient retrieval.
● Dictionaries are used for data indexing and modeling relationships.
Scenarios:
Storing user profiles with keys as user IDs.
Creating a phonebook with keys as contact names.
Representing attributes of a person (name, age, address) with keys.
Practice Exercises:
Exercise 1: Data Structure Comparison
Create a list, a tuple, a set, and a dictionary with relevant data.
Compare and discuss the advantages and disadvantages of each data structure for
each scenario.
3.6 Comprehensions
List comprehensions provide a concise way to create lists. They offer a more readable and
efficient way to generate lists.A single line code.
Example 1:
# List comprehension to generate squares
squares = [x ** 2 for x in range(1, 6)]
# squares = [1, 4, 9, 16, 25]
Example 2: Filtering Odd Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = [num for num in numbers if num % 2 != 0]
# odd_numbers = [1, 3, 5, 7, 9]
Example 3: Creating a List of Strings
fruits = ["apple", "banana", "cherry"]
capitalized_fruits = [fruit.capitalize() for fruit in fruits]
# capitalized_fruits = ["Apple", "Banana", "Cherry"]
Example 4: Generating Tuples
numbers = [1, 2, 3, 4]
tuples = [(num, num ** 2) for num in numbers]
# tuples = [(1, 1), (2, 4), (3, 9), (4, 16)]
Practice Exercises
Exercise 3.6.1: List Comprehension
Create a list of even numbers from 2 to 20 using a list comprehension.
Create a list of squares of odd numbers from 1 to 10 using a list comprehension.
Dictionary Comprehension
Dictionary comprehension is a concise way to create dictionaries in Python by specifying
key-value pairs based on an expression. It follows a similar syntax to list comprehension but
generates dictionaries instead of lists.
Syntax:
{key_expression: value_expression for item in iterable}
Example 1: Creating a Dictionary
numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num ** 2 for num in numbers}
# squared_dict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2: Filtering with a Condition
names = ["Alice", "Bob", "Charlie", "David"]
name_lengths = {name: len(name) for name in names if len(name) > 3}
# name_lengths = {"Alice": 5, "Charlie": 7, "David": 5}
Example 3: Manipulating Values
temperatures = {"Mon": 25, "Tue": 30, "Wed": 28, "Thu": 32}
adjusted_temperatures = {day: temp + 5 for day, temp in temperatures.items()}
# adjusted_temperatures = {"Mon": 30, "Tue": 35, "Wed": 33, "Thu": 37}
Practice Exercises:
Exercise 1: Dictionary Comprehension
❖ Create a dictionary containing the squares of numbers from 1 to 10.
❖ Create a dictionary of even numbers and their squares from 1 to 20.
❖ Create a dictionary with days of the week as keys and their lengths as values.
Exercise 2: Filtering with Condition
❖ Given a list of words, create a dictionary where the keys are words starting with vowels,
and the values are their lengths.
❖ Create a dictionary of prime numbers from 1 to 50 as keys and their squares as values.
Example Project for Section 3: Data Structures in Python
Project: Contact Book Create a program that simulates a contact book using dictionaries. Users
should be able to add, retrieve, and delete contacts.
Project Details:
● Create an empty dictionary for storing contacts.
● Implement options to add, retrieve, and delete contacts.
● Handle potential errors using appropriate error handling techniques.
● Display a list of all contacts in the contact book.