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.

# Creating a list of student names
student_names = ["Alice", "Bob", "Charlie", "David", "Charlie"]

# Adding a student to the list
student_names.append("Eve")

# Removing a student from the list
student_names.remove("Bob")

# Iterating through the list of student names
for name in student_names:
    print(name)

Operations on lists:

  • Accessing elements: student_names[1] returns "Bob".
  • Modifying elements: student_names[0] = "Bryan" changes the first element to Bryan.
  • 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
coordinates = (12.34, 56.78)

# Accessing the longitude and latitude
longitude, latitude = coordinates

# Tuples can be used as keys in dictionaries
capital_cities = {("United States", "California"): "Sacramento", ("France", "Île-de-France"): "Paris"}

# Accessing the capital city of California, United States
capital = capital_cities[("United States", "California")]
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
hobbies_alice = {"reading", "hiking", "cooking"}
hobbies_bob = {"cooking", "painting", "cycling"}

# Finding common hobbies
common_hobbies = hobbies_alice.intersection(hobbies_bob)
print("Common hobbies:", common_hobbies)

# Finding the union of hobbies
all_hobbies = hobbies_alice.union(hobbies_bob)
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, while hobbies_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
student_ages = {"Alice": 20, "Bob": 22, "Charlie": 21}

# Adding a new student to the dictionary
student_ages["David"] = 23

# Updating a student's age
student_ages["Alice"] = 21

# 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"] returns 20.
  • Modifying values: student_ages["Alice"] = 21 changes the value of "Alice" to 21.
  • 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
student_id = "your student id" # @param {type:"string"}
name = "your name" # @param {type:"string"}
# @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
assignment_id = "03-data-structures"
question_id = "00_fun_with_fruits"
submit(student_id, name, assignment_id, ", ".join(fruits), question_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:
coordinates = None

# ---- End of your code ----

print(f"The coordinates for Brussels are {coordinates}")

# Submit Method
assignment_id = "03-data-structures"
question_id = "01_trip_to_brussels"
submit(student_id, name, assignment_id, ", ".join(map(str, coordinates)), question_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
assignment_id = "03-data-structures"
question_id = "02_birthday_party"
submit(student_id, name, assignment_id, str(ages), question_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 = []
odd_count = 0
even_count = 0

# 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
assignment_id = "01-control-structures"
question_id = "03_count-odd-even"
submit(student_id, name, assignment_id, str(odd_count) + ' ' + str(even_count), question_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
Back to top