Skip to the content.

Data Structures

🔗 Lists

We can compose simple data types (e.g., strings, integers, etc) into more complex data structures.

A list, for example, lets us store a sequence of values (often referred to as elements):

pet_names = ['Yogi', 'Boomer', 'Gunther', 'Banana']

You can access and reassign individual positions (or indexes) in a list using square brackets []. NOTE: lists in python always start at 0 (e.g., ‘Yogi’ in our example is at position 0 of the pet_names list).

print(pet_names[0]) # will print Yogi
print(pet_names[1]) # will print Boomer
print(pet_names[3]) # will print Banana

# We can access a list with negative numbers, too...
print(pet_names[-1]) # will print Banana

CHALLENGE QUESTION: how might we get the second-to-last value in the list?

We can modify the value of something in the list:

pet_names[1] = "BOOMER"
print(pet_names[1]) # will print BOOMER

A word of warning: if you try to index into a position beyond the size of the list, python will yell at you: IndexError: list index out of range.

pet_names[4] # will give you an error
pet_names[100] # will give you an error
pet_names[-4] # will give you an error

We can loop over a list using a for loop:

for name in pet_names:
    print(name)

It’s often useful to check to see if a particular value is in the list:

print("'Alex' in the list? " + str('Alex' in pet_names))         # no
print("'Yogi' in the list? " + str('Yogi' in pet_names))         # yes
print("'BANANA' in the list? " + str('BANANA' in pet_names))     # nope - remember, python is case sensitive
print("'gunther' in the list? " + str('gunther' in pet_names))   # nope

We can append things to the end of lists:

pet_names.append("Doggo")
# We can print the entire list
print(pet_names)

We can insert things into the list at a particular position:

pet_names.insert(1, "Fishy")
print(pet_names)

We can remove a particular value from the list:

pet_names.remove("Gunther")
print(pet_names)

We can remove something from the list by position:

pet_names.pop(1)
print(pet_names)

Wait, how long is our list? We can use the len() instruction to check:

list_len = len(pet_names)
print(list_len)
# We could also:
print(len(list_len))

We can sort a list:

sorted_pet_names = sorted(pet_names)
print(sorted_pet_names)

# What if we want reverse order?
reverse_sorted_pet_names = sorted(pet_names, reverse=True)
print(reverse_sorted_pet_names)

We can remove everything from a list:

pet_names.clear()
print(pet_names)

For more things you can do with lists see: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

CHALLENGES

  • Make a list of 10 numbers (of your choosing)
    • calculate the average
    • get the difference between the max and the minimum value

🔗 Dictionaries

We won’t spend much time on dictionaries for the moment, but we’ll point them out because they’re super useful.

A dictionary (often refered to as a dict) in Python is a set of key-value pairs.

In Python, dictionaries are denoted using {}.

info_dict = {"name": "Dumbledore", "age": 115}

In the above example, we created a dictionary with 2 entries with the following keys: "name", "age".

We access the values in a dictionary using their keys:

print(info_dict["name"])                  # Dumbledore
print(info_dict["age"])                   # 115

We can update the value associated with a particular key:

info_dict["name"] = "Harry Potter"
print(info_dict["name"])            # Harry Potter

We can add entries to a dictionary:

info_dict["muggle"] = False
print(info_dict)

CHALLENGE: Entries in a dictionary can have different types, not just numbers and strings. Make a dictionary where at least one entry has a list for a value and another entry has a dictionary for a value.

For more on dictionaries: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

🔗 Data structures - example games

🔗 World guessing game

In the word guessing game, the programmer has selected a secret word, and the player has 10 rounds to guess reveal what the secret is by guessing one letter at a time.

🔗 Simon Says

Game description:

Simon says is played in rounds. Starting the game with and empty list, the program selects a random letter each round. The program prints the chosen letter for the player to see. The player must then input each letter that the program previously output. Any deviation from the correct sequence results in a loss. The player’s goal is to achieve as high a score as possible.

Example gameplay:

Simon says:  B
> B
Simon says: C
> B
> C
Simon says: A
> B
> C
> A
Simon says: C
> B
> C
> A
> C
Simon says: D
> C
WRONG! Final score = 4

In the above example, the program output all of the ‘simon says’ lines (using print("Simon says:", letter)), and player input (using input(">")) is given after the ‘>’ prompt. When the player fails to repeat the full sequence, the player loses, and the game reports their final score.

If you have extra time, you can consider making the following changes:

  • Ensure that the user is only allowed to select a valid option (prompting them again if necessary)
  • Change the elements that are being tested to (‘Rock’, ‘Paper’, or ‘Scissors’)
  • For each input, let the player know how many more letters they need to provide for the round.
  • Be sure to partition your code into functions with clear names and documentation

🔗 Example - Intro to lists:

Here’s our list example from the 2021 camp:

# We can use lists to store collections of values!
# Lists are denoted by square brackets [ ]
# Lists can contain strings:
high_scorer_list = ["Austin", "Matthew", "Santiago", "Josh"]
# Or integers:
score_list = [1200, 1159, 900, 12]
# Or a mix of types:
mix_list = ['string', 12, 3.14]

# Here's what it looks like to print a list:
print('Original list:')
print(high_scorer_list)
# We can index into a list with [ ]
# NOTE: indices start at 0!
print('First item:', high_scorer_list[0]) # First
print('Third item:', high_scorer_list[2]) # Third
print('Fourth item:', high_scorer_list[3]) # Fourth

# Negative indices access the end of the list!
print('Last item:', high_scorer_list[-1]) # Last item in list
print('Next to last item:', high_scorer_list[-2]) # Next to last item in list

# We can't ask for an index past the end of the list!
# If uncommented, these will cause an error!
#print(high_scorer_list[100])
#print(high_scorer_list[-100])

print('----')
# We can use a for loop to iterate through the items (i.e., elements) in a list:
print('Iterating through items in the list:')
for name in high_scorer_list:
    print(name + ' has a great score!')

print('----')
print('Current list:')
print(high_scorer_list)
print('Adding item "Anna"')
high_scorer_list.append('Anna')
print(high_scorer_list)
print('Adding item "JV" at index 0 (start of list)')
high_scorer_list.insert(0, 'JV')
print(high_scorer_list)
print('Removing "Josh from list"')
high_scorer_list.remove('Josh')
print(high_scorer_list)

# Get the number of items in the list using len:
print("Length of list:", len(high_scorer_list))

print('----')
print('Current state of the list:')
print(high_scorer_list)
# We can clear the list using either of these lines:
high_scorer_list.clear()
high_scorer_list = []
print('After clearing the list: ')
print(high_scorer_list)

🔗 Example - Max of list:

# A list of integers...
num_list = [5, 2, 10, 67, 12, 2, 5, 8]
print('Our list of numbers:')
print(num_list)

# For all problems:
#   Assume all values are between 0 and 100

# Get the maximum value in the list!
max_num = -1
for num in num_list: 
    if num > max_num: 
        max_num = num
print('Maximum value:', max_num)
print('Maximum value using max function: ', max(num_list))


# Challenges:

#   1. Find the MINIMUM of the list
min_num = 101 
for num in num_list: 
    if num < min_num: 
        min_num = num
print('Minimum value:', min_num)
print('Minimum value using min function:', min(num_list))

#   2. Find the AVERAGE of the list
total = 0
for num in num_list: 
    total = total + num
print('Average value:', total / len(num_list))
print('Average value using sum function:', sum(num_list) / len(num_list))

print('We can also sort the list:')
sorted_list = sorted(num_list)
print(sorted_list)
print('Minimum value (first item in sorted list):', sorted_list[0])

🔗 Example - Lists + Random

import random

# Let's store color names in a list!
color_list = ['red', 'green', 'blue', 'yellow', 'orange']
print("Here's our list of colors:")
print(color_list)

print("Using random.choice() to get 15 random colors:")
for i in range(15):
    print(random.choice(color_list))

print('-----')
print('We can also shuffle our list!')
print('Original:', color_list)
random.shuffle(color_list)
print('Shuffled:', color_list

🔗 Extra example - List of lists

# We can create a "list of lists"
#   Here, each element in the list is a list itself
high_score_list = [
    ["Austin", 1200], 
    ["Matthew", 1199], 
    ["Michelle", 1150]]

print('Here is our "list of list" high score table:')
print(high_score_list)
print('Here is the second element in the list: ')
print(high_score_list[1])


total = 0
print('We can still iterate through our list:')
for sub_list in high_score_list:
    print('Element as it appears in the list:', sub_list)
    name = sub_list[0]
    score = sub_list[1]
    total = total + score
    # We can print it prettier:
    print(name + ' scored ' + str(score))
print('Average score:', total / len(high_score_list))