# Creating a list of student names
= ["Alice", "Bob", "Charlie", "David", "Charlie"]
student_names
# Adding a student to the list
"Eve")
student_names.append(
# Removing a student from the list
"Bob")
student_names.remove(
# Iterating through the list of student names
for name in student_names:
print(name)
Data Structures
Data structures are essential for organizing, managing, and storing data in a program. Python provides built-in data structures like Lists, Tuples, Sets, and Dictionaries that offer different functionalities and use cases. For more information on Python data structures and their methods, you can visit learnpython.
List
- Ordering: Lists are ordered collections.
- Mutability: Lists are mutable; they can be modified after creation.
- Duplicates: Lists allow duplicate elements.
- Syntax: Lists are created using square brackets
[]
.
A common use case for lists is storing and accessing a collection of items in a specific order.
Operations on lists:
- Accessing elements:
student_names[1]
returns"Bob"
. - Modifying elements:
student_names[0] = "Bryan"
changes the first element toBryan
. - Adding elements:
student_names.append("Eric")
adds"Eric"
to the end of the list. - Removing elements:
student_names.remove("Charlie")
removes the first occurrence of"Charlie"
from the list.
Tuples
- Ordering: Tuples are ordered collections.
- Mutability: Tuples are immutable; they cannot be modified after creation.
- Duplicates: Tuples allow duplicate elements.
- Syntax: Tuples are created using round brackets
()
.
Tuples are useful when you have a fixed collection of items that should not change throughout the program’s execution.
# Defining coordinates as a tuple
= (12.34, 56.78)
coordinates
# Accessing the longitude and latitude
= coordinates
longitude, latitude
# Tuples can be used as keys in dictionaries
= {("United States", "California"): "Sacramento", ("France", "Île-de-France"): "Paris"}
capital_cities
# Accessing the capital city of California, United States
= capital_cities[("United States", "California")]
capital print(capital)
Sets
- Ordering: Sets are unordered collections.
- Mutability: Sets are mutable; they can be modified after creation.
- Duplicates: Sets do not allow duplicate elements.
- Syntax: Sets are created using curly brackets
{}
.
Sets are useful for efficiently storing unique values and performing set operations.
# Creating sets of unique hobbies for two people
= {"reading", "hiking", "cooking"}
hobbies_alice = {"cooking", "painting", "cycling"}
hobbies_bob
# Finding common hobbies
= hobbies_alice.intersection(hobbies_bob)
common_hobbies print("Common hobbies:", common_hobbies)
# Finding the union of hobbies
= hobbies_alice.union(hobbies_bob)
all_hobbies print("All hobbies:", all_hobbies)
Operations on sets:
- Adding elements:
hobbies_alice.add("riding")
adds"riding"
to the set. - Removing elements:
hobbies_alice.remove("hiking")
removes"hiking"
from the set. - Unions and intersections:
hobbies_alice.union(another_set)
returns a new set containing elements from both sets, whilehobbies_alice.intersection(another_set)
returns a new set containing common elements.
Dictionaries
- Ordering: Dictionaries are unordered collections.
- Mutability: Dictionaries are mutable; they can be modified after creation.
- Duplicates: Dictionaries do not allow duplicate keys, but values can be duplicated.
- Structure: Dictionaries consist of key-value pairs.
- Syntax: Dictionaries are created using curly brackets {} with key-value pairs separated by colons.
Dictionaries are useful for storing key-value pairs and efficiently accessing values using their keys.
# Creating a dictionary that maps student names to their ages
= {"Alice": 20, "Bob": 22, "Charlie": 21}
student_ages
# Adding a new student to the dictionary
"David"] = 23
student_ages[
# Updating a student's age
"Alice"] = 21
student_ages[
# Iterating through the dictionary and printing student names and ages
for name, age in student_ages.items():
print(name, "is", age, "years old")
Operations on dictionaries:
- Accessing values:
student_ages["Alice"]
returns20
. - Modifying values:
student_ages["Alice"] = 21
changes the value of"Alice"
to21
. - Adding key-value pairs:
student_ages["Fulan"] = 20
adds a new key-value pair to the dictionary. - Removing key-value pairs:
student_ages.pop("Fulan")
removes the key-value pair with the key"Fulan"
.
Exercise Data Structures
!pip install rggrader
# @title #### Student Identity
= "your student id" # @param {type:"string"}
student_id = "your name" # @param {type:"string"} name
# @title #### 00. Fun with Fruits
from rggrader import submit
# TODO: Create a list 'fruits' that contains "Apple", "Banana", and "Cherry".
# Then remove "Banana" from the 'fruits' list and append "Dragonfruit" and "Elderberry".
= []
fruits
# Put your code here:
# ---- End of your code ----
print(f"The final fruits list is {fruits}")
# Submit Method
= "03-data-structures"
assignment_id = "00_fun_with_fruits"
question_id ", ".join(fruits), question_id)
submit(student_id, name, assignment_id,
# Example:
# List: ["Peach", "Pear", "Plum"]
# Remove: "Pear"
# Append: ["Grape", "Guava"]
# Output: ['Peach', 'Plum', 'Grape', 'Guava']
# @title #### 01. Trip to Brussels
from rggrader import submit
# TODO: You're planning a trip to Brussels! Create a tuple 'coordinates' that represents a longitude
# of 50.85 and a latitude of 4.35 (which is the coordinates of Brussels).
# Put your code here:
= None
coordinates
# ---- End of your code ----
print(f"The coordinates for Brussels are {coordinates}")
# Submit Method
= "03-data-structures"
assignment_id = "01_trip_to_brussels"
question_id ", ".join(map(str, coordinates)), question_id)
submit(student_id, name, assignment_id,
# Example:
# Longitude: 60.17
# Latitude: 24.94
# Output: (60.17, 24.94)
# @title #### 02. Birthday Party
from rggrader import submit
# TODO: You're throwing a birthday party! Create a dictionary 'ages' that contains key-value pairs of your friends' names
# and their ages: "Alice": 25, "Bob": 30, "Charlie": 35.
# Alice just had her birthday! So, change the age of "Alice" to 26. Then, add your friend "David" who is 40 to the party.
# Put your code here:
= {}
ages
# ---- End of your code ----
print(f"The final ages dictionary is {ages}")
# Submit Method
= "03-data-structures"
assignment_id = "02_birthday_party"
question_id str(ages), question_id)
submit(student_id, name, assignment_id,
# Example:
# Dictionary: {"John": 28, "Linda": 25, "Peter": 30}
# Change Age: John turns 29
# Add New Friend: {"Mary": 32}
# Output: {"John": 29, "Linda": 25, "Peter": 30, "Mary": 32}
# @title #### 03. Count Odd and Even
from rggrader import submit
# TODO: Create a list 'series' that contains the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9.
# Write a program to count the number of odd and even numbers from a series of numbers.
= []
series = 0
odd_count = 0
even_count
# Put your code here:
# ---- End of your code ----
print(f"The count of odd numbers is {odd_count} and the count of even numbers is {even_count}")
# Submit Method
= "01-control-structures"
assignment_id = "03_count-odd-even"
question_id str(odd_count) + ' ' + str(even_count), question_id)
submit(student_id, name, assignment_id,
# Example:
# Series: [2, 4, 6, 7, 9, 11, 13, 15]
# Output: The count of odd numbers is 5 and the count of even numbers is 3