5. Lists, Tuples, Dictionary, and Sets#
Lists:#
A list is a mutable, ordered collection of items. It allows you to add, remove, or modify elements after the list is created. Lists are dynamic in nature, which means their size can change during runtime. The items in a list can be of any data type, including other lists or tuples. Lists are created using square brackets [], and elements are separated by commas.
A simple exercise to help you understand Python lists. Let’s create a program that performs various operations on a list of numbers.#
Create a list of numbers.
Calculate the sum of all the numbers in the list.
Find the maximum and minimum values in the list.
Reverse the order of the list.
Remove duplicates from the list.
# 1. Create a list of numbers
numbers = [5, 3, 7, 2, 8, 3, 10, 5, 1, 8]
# 2. Calculate the sum of all the numbers in the list
total = sum(numbers)
print("Sum of all numbers:", total)
Sum of all numbers: 52
# 3. Find the maximum and minimum values in the list
maximum = max(numbers)
minimum = min(numbers)
print("Max value:", maximum)
print("Min value:", minimum)
Max value: 10
Min value: 1
# 4. Reverse the order of the list
numbers.reverse()
print("Reversed list:", numbers)
Reversed list: [8, 1, 5, 10, 3, 8, 2, 7, 3, 5]
# 5. Remove duplicates from the list
unique_numbers = list(set(numbers))
print("List without duplicates:", unique_numbers)
List without duplicates: [1, 2, 3, 5, 7, 8, 10]
# Create a list of integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Initialize an empty list to store the updated numbers
updated_numbers = []
# Use a for loop to iterate over the original list
for number in numbers:
# Check if the number is even
if number % 2 == 0:
# Double the value and append it to the new list
updated_numbers.append(number * 2)
else:
# Append the original number
updated_numbers.append(number)
# Print the updated list
print("Updated list:", updated_numbers)
Updated list: [1, 4, 3, 8, 5, 12, 7, 16, 9]
Exercises#
Problem
: Square odd numbers and halve even numbers in a list
Given a list of integers, create a new list that squares the value of every odd number in the original list and halves the value of every even number.
Create a list of integers containing both positive and negative numbers.
Initialize an empty list to store the updated numbers.
Use a for loop to iterate over the original list.
For each number, check if it’s odd.
If it’s odd, square its value and append it to the new list; otherwise, halve the value and append it to the new list.
Print the updated list.
# Problem: Square odd numbers and halve even numbers in a list
# 1. Create a list of integers
# ...
# 2. Initialize an empty list to store the updated numbers
# ...
# 3. Use a for loop to iterate over the original list
# ...
# 4. Check if the number is odd
# ...
# 5. If it's odd, square its value and append it to the new list; otherwise, halve the value and append it to the new list
# ...
# 6. Print the updated list
# ...
# Output: ...
Tuples:#
A tuple is an immutable, ordered collection of items. Once a tuple is created, you cannot change its contents or size. Tuples are fixed-size and often used when you need an immutable sequence of values. Like lists, tuples can store items of any data type, including other lists or tuples. Tuples are created using parentheses () with elements separated by commas, or simply by separating elements with commas (without using parentheses).
A simple exercise to help you understand Python lists. Let’s create a program that performs various operations on a list of numbers.#
Create a list of numbers.
Calculate the sum of all the numbers in the list.
Find the maximum and minimum values in the list.
Reverse the order of the list.
Remove duplicates from the list.
# 1. Create a tuple of different data types
my_tuple = (42, 3.14, "hello", True, 42)
# 2. Access elements in the tuple using indices
print("First element:", my_tuple[0])
print("Second element:", my_tuple[1])
print("Last element:", my_tuple[-1])
First element: 42
Second element: 3.14
Last element: 42
# 3. Calculate the length of the tuple
length = len(my_tuple)
print("Length of the tuple:", length)
Length of the tuple: 5
# 4. Count the occurrences of a specific value in the tuple
occurrences = my_tuple.count(42)
print("Occurrences of 42 in the tuple:", occurrences)
Occurrences of 42 in the tuple: 2
# 5. Find the index of a specific value in the tuple
index = my_tuple.index("hello")
print("Index of 'hello' in the tuple:", index)
Index of 'hello' in the tuple: 2
The main difference between lists and tuples in Python is their mutability:#
Mutability:
Lists
are mutable, which means you can change their contents (add, remove, or modify elements) after they are created. They are dynamic data structures and their size can also be changed during runtime.Tuples
are immutable, which means once they are created, you cannot change their contents or size. Their elements and structure are fixed for the lifetime of the tuple.
Syntax:
Lists
are created using square brackets [] and elements are separated by commas. For example: my_list = [1, 2, 3].Tuples
are created using parentheses () with elements separated by commas, or simply by separating elements with commas (without using parentheses). For example: my_tuple = (1, 2, 3) or my_tuple = 1, 2, 3.
Performance:
Tuples
generally have a smaller memory footprint and better performance than lists for certain operations, such as iteration and access by index, due to their immutability. This makes them suitable for use as keys in dictionaries or elements in sets.Lists
are more flexible and versatile than tuples, but their mutability can lead to higher memory usage and slower performance for certain operations.
In summary, you should choose to use a list when you need a mutable, dynamic data structure that can be modified during runtime, and a tuple when you need an immutable, fixed-size data structure for efficient operations and improved performance.
Dictionary#
A Python dictionary is a mutable, unordered collection of key-value pairs, where each unique key is associated with a value. Dictionaries are implemented as hash tables, which provide fast access, insertion, and deletion of elements. They are a built-in data structure in Python and are commonly used for tasks such as counting, grouping, and organizing data, or for creating lookup tables.
Here’s an example of a Python dictionary:
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"occupation": "Software Engineer"
}
In this example, the keys are “name”, “age”, “city”, and “occupation”, and their respective values are “Alice”, 30, “New York”, and “Software Engineer”. To access the values, you can use the keys like this:
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
Alice
30
book = {
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"year_published": 1960,
"genres": ["Southern Gothic", "Bildungsroman"],
"page_count": 281
}
print(book["title"]) # Output: To Kill a Mockingbird
print(book["year_published"]) # Output: 1960
To Kill a Mockingbird
1960
key = "publisher"
if key in book:
print(f"{key}: {book[key]}")
else:
print(f"{key} is not available in the book dictionary.")
publisher is not available in the book dictionary.
Here’s a simple function that uses a dictionary to store and retrieve a person’s age based on their name:
def get_age(people, name):
if name in people:
return f"{name} is {people[name]} years old."
else:
return f"{name} is not in the dictionary."
people = {
"Alice": 30,
"Bob": 28,
"Charlie": 22
}
name = "Alice"
print(get_age(people, name)) # Output: Alice is 30 years old.
name = "David"
print(get_age(people, name)) # Output: David is not in the dictionary.
Alice is 30 years old.
David is not in the dictionary.
Exercise 1#
Task
: Write a Python function called get_grade that takes a dictionary grades and a student’s name as arguments. The function should return the grade of the student if their name is found in the dictionary, or a message indicating that the student’s name is not in the dictionary if it isn’t found.
grades = {
"Alice": "A",
"Bob": "B",
"Charlie": "C"
}
Example usage:
print(get_grade(grades, "Alice")) # Output: Alice's grade is A.
print(get_grade(grades, "David")) # Output: David is not in the dictionary.
def get_grade(grades, name):
# Your code here
grades = {
"Alice": "A",
"Bob": "B",
"Charlie": "C"
}
name = "Alice"
print(get_grade(grades, name))
name = "David"
print(get_grade(grades, name))
Exercise 2#
def add_student(students, name, age):
# Your code here
students = {
"Alice": 30,
"Bob": 28,
"Charlie": 22
}
name = "David"
age = 25
students = add_student(students, name, age)
name = "Alice"
age = 30
students = add_student(students, name, age)
print(students)
Cell In[21], line 4
students = {
^
IndentationError: expected an indented block after function definition on line 1
Set#
A Python set is an unordered collection of unique elements, which means that each element can only appear once in a set. Sets are mutable, meaning that elements can be added or removed after the set is created. They are particularly useful when you need to remove duplicates from a sequence or check membership of elements efficiently.
Here’s an example of a Python set:
animals = {"cat", "dog", "elephant", "tiger"}
animals.add("giraffe")
animals.remove("cat")
print("dog" in animals) # Output: True
True
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
union = set_a | set_b # or set_a.union(set_b)
intersection = set_a & set_b # or set_a.intersection(set_b)
difference = set_a - set_b # or set_a.difference(set_b)
Exercise 1: Remove duplicates from a list#
Given a list of numbers, create a new list with all the unique elements from the original list (i.e., remove all duplicates).
Example:
original_list = [1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9]
# Expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Exercise 2: Find common elements between two lists#
Given two lists of numbers, create a new list containing the common elements between the two lists (i.e., elements that appear in both lists).
Example:
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
# Expected output: [4, 5]