Chapter 2: Lists, Dictionaries and Sets

Chapter 2: Lists, Dictionaries and Sets

2.1 Lists

Lists are used to store multiple items in a single variable.

Let’s think about a real example

Imagine you are writing a shopping list:

  • Apples
  • Bananas
  • Chocolate

Instead of creating a separate variable for each item, we can store all of them together in a single structure.

How can we translate this into Python?

# This is the way to write a shopping list in python
shopping_l = ["apple", "banana", "chocolate"]
print(shopping_l)

What is happening here?

  • Square brackets [] define a list
  • Each item is separated by a comma
  • The list keeps the order of the elements

👉 Now all items are stored in a single variable: shopping_l


A list has the following properties:

2.1.1 Ordered

Items have a defined order, and this order will not change. This means we can access elements by their position (index)

—- Let’s do an example! —-

Imagine we want to extract apple from the shopping list

# apple is in position 0 then...
shopping_l = ["apple", "banana", "chocolate"]
print(shopping_l[0])

Can we get apple with negative indices? Write the answer below

# Write your answer here

2.1.2 Changeable (Mutable)

Lists can be modified after they are created.

—- Let’s do an example! —-

Imagine we want to change apple by cheese in our shopping list

shopping_l = ["apple", "banana", "chocolate"]
shopping_l[0] = "cheese"   # change item
print(shopping_l)

—- Let’s do another example! —-

Imagine that instead of changing apples by cheese, we want to add cheese in our shopping list

# We can use append!
shopping_l = ["apple", "banana", "chocolate"]
shopping_l.append("cheese")
print(shopping_l)

Question: What do you think that will happen with the next piece of code?

shopping_l = ["apple", "banana", "chocolate"]
print(shopping_l+"cheese")

This won’t work! It will work only if we combine two lists, not a list with a string. Appropiate way of doing it:

shopping_l = ["apple", "banana", "chocolate"]
print(shopping_l+["cheese"])

2.1.3 Allow duplicates

Lists can contain the same item more than once.

shopping_l = ["apple", "banana", "apple"]
print(shopping_l)

2.1.4 Length

Sometimes we want to know how many items are in a list. For this, we use the len() function.

—- Let’s do an example! —-

How many items are in my current list now?

shopping_l = ["apple", "banana", "chocolate"]
# len returns the number of elements in the list
print(len(shopping_l))

Question: What would len([]) return?

Question: What would be the length of this list? l = [“apple”, “banana”, apple”]

Write your answers here

2.1.5 List slicing

Just like strings, we can extract parts of a list using slicing. The syntax is:

list[start:end]

  • start → included
  • end → NOT included

—- Let’s do an example! —-

We want to buy only a banana and chocolate

shopping_l = ["apple", "banana", "chocolate", "cheese"]
print(shopping_l[1:3])

–> What is happening here?

We are selecting elements from index 1 to 3 (not included):

[“banana”, “chocolate”]

–> Visual representation

Index: 0 1 2 3
Items: apple banana chocolate cheese

shopping_l[1:3] → [“banana”, “chocolate”]

2.2 Dictionaries

A data structure that stores information in key-value pairs.

  • Key → a unique identifier for an item
  • Value → the data associated with that key

IMAGE OF A CALENDAR WHERE KEYS ARE DAYS AND VALUES ARE ACTIVITIES !!!

2.2.1 Creating a dictionary

We will create a calendar using a python dictionary

# Keys: "Monday", "Tuesday"
# Values: "Gym", "Bioinformatics"
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
print(d)

What is happening here?

  • {} → defines a dictionary
  • Each key is followed by a colon : and its value
  • Items are separated by commas

Other ways of creating a dictionary

A dictionary can also be created using the dict() function.

d = dict(Monday='Gym',Tuesday='Bioinformatics')
print(d)

2.2.2 Accessing dictionary items

A value in a dictionary is accessed by using its key.

There are two main options:

  1. Using square brackets []
  2. Using the get() method

—- Let’s do an example! —-

Imagine we want to know the activity we will do on Monday

# Option 1
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
print(d['Monday'])

What is happening here?

  • We use the key "Monday" inside square brackets
  • Returns the value associated with the key: "class"

Let’s do the same with the get method!

# Option 2
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
print(d.get('Monday'))

—- Let’s do another example! —-

Imagine we want to know the activity we will do on Wednesday

d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
print(d.get('Wednesday'))

What is happening here?

  • .get(key) returns the value for the key
  • If the key does not exist, it returns None (or a default value if provided)
  • Safer than using [] when the key might not be present

2.2.3 Adding Dictionary Items

New items are added to a dictionary using the assignment operator (=) by giving a new key a value.

—- Let’s do an example! —-

Imagine we want to add an activity (UBDS) to our calendar

d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
d['Wednesday'] = 'UBDS'
print(d)

What is happening here?

  • d["Wednesday"] = "UBDS" → adds a new key "Wednesday" with value "UBDS"
  • Existing keys remain unchanged
  • The dictionary now contains three key-value pairs:
{"Monday": "Gym", "Tuesday": "Bioinformatics", "Wednesday": "UBDS"}

2.2.4 Updating Dictionary Items

If an existing key is used with the assignment operator, its value is updated with the new one.

—- Let’s do an example! —-

Instead of assigning UBDS to a new day (Wednesday) we want to assign it to Monday

d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
d['Monday'] = 'UBDS'
print(d)

What is happening here?

  • "Monday" already exists in the dictionary
  • Assigning a new value "UBDS" replaces the old value "Gym"
  • Result:
{"Monday": "UBDS", "Tuesday": "Bioinformatics", "Wednesday": "UBDS"}

Question: What would happen with the next code?

d = {"Monday": "UBDS", "Tuesday": "Bioinformatics", "Wednesday": "UBDS"}
d['tuesday'] = 'Basketball'
# Write your answer here

2.2.5 Removing Dictionary Items

Dictionary items can be removed using built-in deletion methods that work on keys:

  • del: removes an item using its key
  • pop(): removes the item with the given key and returns its value
  • clear(): removes all items from the dictionary
  • popitem(): removes and returns the last inserted key–value pair
# Using del
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
del d['Monday']
print(d)

What is happening here?

  • del d["Monday"] removes the key "Monday" and its value
  • The dictionary now only has "Tuesday"
# Using pop
# Remove and get the value of Monday
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
removed_value = d.pop("Monday")
print("Removed:", removed_value)
print(d)

What is happening here?

  • pop("Monday") removes "Monday" and returns its value "Gym"
  • Useful when you need the removed value for further use
# Using popitem()
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
last_item = d.popitem()
print("Removed last item:", last_item)
print(d)

What is happening here?

  • popitem() removes the last inserted key–value pair
  • Returns a tuple (key, value)
  • Very useful to remove items in LIFO order
# Using clear()
d = {"Monday":'Gym','Tuesday':'Bioinformatics'}
d.clear()
print(d)

What is happening here?

  • clear() removes all items from the dictionary
  • The dictionary becomes empty: {}
  • Useful for resetting a dictionary

Answer the following questions

  1. What will happen if you del a key that does not exist?
  2. How is pop() different from del?
  3. What will popitem() return if the dictionary is empty?
# Write your answer here

Answer here

2.2.6 Nested Dictionaries

Dictionary that contains another dictionary as one of its values.

—- Let’s do an example! —-

Let’s get our calendar. Imagine that on wednesday we have two activities: one in the morning and one in the afternoon. To write is as a dictionary we should do the following code:

d = {
    "Monday": "Gym",
    "Tuesday": "Bioinformatics",
    "Wednesday": {
        "Morning": "Coding",
        "Afternoon": "Basketball"
    }
}

print(d)

What is happening here?

  • "Wednesday" has a dictionary as its value
  • The inner dictionary has two keys: "Morning" and "Afternoon"
  • Each inner key has its own value
  • This structure allows storing more detailed information for a single day

To access the values:

# Get Wednesday's morning activity
print(d["Wednesday"]["Morning"])  # Coding

# Get Wednesday's afternoon activity
print(d["Wednesday"]["Afternoon"])  # Basketball

Answer the following questions

  1. How would you add an "Evening" activity to Wednesday?

Answer here

2.3 Sets

A set is a data structure used to store multiple items in a single variable.

👉 The key difference from lists:

Sets do NOT allow duplicate values

—- Let’s do an example! —-

Imagine your shopping list has duplicates:

apple
banana
apple
chocolate

👉 Do we really need “apple” twice?

# Using a list
l = ["apple", "banana", "apple", "chocolate"]
print(l)
# Using a set
s = {"apple", "banana", "apple", "chocolate"}
print(s)

What is happening here?

  • Duplicates are automatically removed
  • The set keeps only unique values

Result: {“apple”, “banana”, “chocolate”}

Important: Sets are unordered

Unlike lists, sets do NOT keep the order of elements. You cannot access elements by index

Key properties of sets

  • ❌ No duplicates
  • ❌ No indexing
  • ✔️ Fast operations (useful for checking membership)

—- Let’s do an example! —-

Imagine we want to check in an item exists or not

s = {"apple", "banana", "chocolate"}

print("apple" in s)   # True
print("milk" in s)    # False

Answer the following questions

  • Can we do s[0]? Why?
# Write your answer here

2.3.1 Heterogeneous sets

Sets can store elements of different data types.

s = {"apple", 10, 3.14, True}
print(s)

What is happening here?

  • A set can contain strings, numbers, booleans, etc.
  • However, all elements must be hashable (we won’t go deep into this for now)

You cannot store mutable types like lists inside a set!!!

2.3.2 Frozen sets

A frozenset is an immutable version of a set. Once created, it cannot be changed

fs = frozenset(["apple", "banana", "chocolate"])
print(fs)

What is happening here?

  • Similar to a set, but:
    • ❌ cannot add elements
    • ❌ cannot remove elements

Useful when you want a set that should not change

2.3.3 Set methods

There are different methods that we can apply to sets: * Adding elements to sets * Union of sets * Intersection of sets * Difference of sets

—- Let’s do an example! —-

Imagine we have a shopping list without duplicates:

shopping_s = {"apple", "banana", "chocolate"}
print(shopping_s)

And we want to add “cheese” to our shopping list

# Adding cheese
shopping_s = {"apple", "banana", "chocolate"}
shopping_s.add("cheese")
print(shopping_s)

Question: What happens if we try to add “apple” again?

# Write your answer here

—- Let’s do another example! —-

Imagine we have a shopping list without duplicates as before, but now your friend gives you their shopping list:

friend_s = {"banana", "milk", "bread"}

And you want to create a single unified shopping list

shopping_s = {"apple", "banana", "chocolate"}
friend_s = {"banana", "milk", "bread"}
print(shopping_s.union(friend_s))

What is happening here?

  • Combines both shopping lists
  • Duplicates are automatically removed

—- Let’s do another example! —-

Imagine we have a shopping list without duplicates as before, but now your friend gives you their shopping list:

friend_s = {"banana", "milk", "bread"}

But now you want to find the common elements between your shopping lists

shopping_s = {"apple", "banana", "chocolate"}
friend_s = {"banana", "milk", "bread"}
print(shopping_s.intersection(friend_s))

—- Let’s do another example! —-

Imagine we have a shopping list without duplicates as before, but now your friend gives you their shopping list:

friend_s = {"banana", "milk", "bread"}

And you want to know which items are only in your list but NOT in your friend’s?

shopping_s = {"apple", "banana", "chocolate"}
friend_s = {"banana", "milk", "bread"}
print(shopping_s.difference(friend_s))

2.4 Exercises

Exercise 1

You are given a list of DNA sequences:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Print the first sequence
  2. Print the last sequence
  3. Print the first 3 nucleotides of the first sequence
  4. Print the length of the second sequence
# Write your answer here

Exercise 2

Using the same list:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Replace the second sequence with “GGGAAA”
  2. Add a new sequence “TTTCCC”
  3. Print the updated list
# Write your answer here

Exercise 3

You are given a list with repeated sequences:

seqs = ["ATGCGT", "ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Convert the list into a set
  2. Print the result
  3. How many unique sequences are there?
# Write your answer here

Exercise 4

You are given a dictionary with sequence names and sequences:

data = {
    "seq1": "ATGCGT",
    "seq2": "TTAGGC",
    "seq3": "CCGTAA"
}

Tasks:

  1. Print the sequence of “seq1”
  2. Print the sequence of “seq3”
  3. Add a new sequence: “seq4”: “GGGAAA”
  4. Update “seq2” to “TTTTTT”
# Write your answer here

Exercise 5

You are given a nested dictionary:

fasta = { “seq1”: {“sequence”: “ATGCGT”, “length”: 6}, “seq2”: {“sequence”: “TTAGGCA”, “length”: 7} }

Tasks:

  1. Print the sequence of “seq1”
  2. Print the length of “seq2”
  3. Add a new key “species”: “human” to “seq1”
# Write your answer here