8. Storing Multiple Data

This lesson will cover new variables that can be used to store multiple data.

Lists

Lists are created from square brackets and are used to store multiple items in a single variable. Some properties of lists is they are ordered, changeable, and allow duplicate values. Like strings, lists can be indexed with square brackets. Below is an example of a list:

days_of_the_week = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
print(days_of_the_week)
print(days_of_the_week[0])

Notice how the indexing starts at 0.

All the slicing rules for strings apply to lists.

To change a list you can either set, insert, append, extend, remove, pop, or clear. To set a list, index a location and then set that equal to some value. To insert at a specific index, use the insert function. To append (add to the list at the end), use the append function. Extending combines two multiple data variables, and is done with the extend function. To remove is done with the remove statement. Popping removes at a specific index, and is done with the pop function. To clear the list, use the clear function. Below is an example of all of these being used:

names = ["Bill", "Bob", "Andrew"]
print(names) # ["Bill", "Bob", "Andrew"]

names[0] = "Jeff"
print(names) # ["Jeff", "Bob", "Andrew"]

names.insert(1, "Ella")
print(names) # ["Jeff", "Ella", "Bob", "Andrew"]

names.append("Michael")
print(names) # ["Jeff", "Ella", "Bob", "Andrew", "Michael"]

not_names = ["Dog", "Cat"]
names.extend(not_names)
print(names) # ["Jeff", "Ella", "Bob", "Andrew", "Michael", "Dog", "Cat"]

names.remove("Cat")
print(names) # ["Jeff", "Ella", "Bob", "Andrew", "Michael", "Dog"]

names.pop(5)
print(names) # ["Jeff", "Ella", "Bob", "Andrew", "Michael"]

names.clear()
print(names) # []

Notice how to call a function on the list there is a dot.

When you pop with no specified index, it removes the last index.

To get the length of a list use the len function. Here is an example:

lst = [300, "hello", True, 1.5]
print(len(lst)) # 4

Notice how lists can store multiple different types of data.

The len function also works to get the length of a string.

Sets

Another way to store multiple data is with a set. Sets are written with curly brackets and are unordered, not indexed, unchangeable, and does not allow duplicates. To get the length of a set use the len function. Below is an example of a set:

fruits = {"apple", "banana", "cherry"}
print(fruits) # {"apple", "banana", "cherry"}

Although sets are unchangeable, you can still add and remove to them. To add, use the add function. To combines two multiple data variables, use the update function. To remove, use the remove function. To discard, use the discard function. The difference between remove and discard is if an item does not exist, remove will raise an error but discard won't. You can also use the pop function but it only removes the last thing in the set. To clear, use the clear function. Here are some examples:

fruits = {"apple", "banana", "cherry"}
print(fruits) # {"apple", "banana", "cherry"}

fruits.add("pear")
print(fruits)

more_fruits = ["avocado", "cucumber"]
fruits.update(more_fruits)
print(fruits)

fruits.remove("avocado")
print(fruits)

fruits.discard("pear")
print(fruits)

fruits.pop()
print(fruits)

fruits.clear()
print(fruits)

Tuples

Another way to store multiple data is with a tuple. Tuples are written with round brackets and are ordered, unchangeable and allow duplicates. You can index tuples just like lists and strings. Here is an example of a tuple:

places = ("beach", "house", "school")
print(places) # ("beach", "house", "school")

Tuples are unchangeable but there is a way to still change them. In order to change a tuple you have to first convert it to a list and then back into a tuple. To get the length of a tuple use the len function. Here is an example of appending:

places = ("beach", "house", "school")
print(places) # ("beach", "house", "school")

places_lst = list(places)
places_lst.append("park")
places = tuple(places_lst)
print(places) # ("beach", "house", "school", "park")

Note how the converting into a list or tuple is the same thing as casting.

To combine tuples concatenate two or more tuples. You can also multiply the tuple. Here are some examples:

places = ("beach", "house", "school")
print(places) # ("beach", "house", "school")

more_places = ("restaurant", "pool")
places += more_places
print(places) # ("beach", "house", "school", "park", "restaurant", "pool")

places *= 2
print(places) # ("beach", "house", "school", "park", "restaurant", "pool", "beach", "house", "school", "park", "restaurant", "pool")

You can also "unpack" a tuple. When you create a tuple you pack it and then you can unpack the values in a tuple. Below is an example of unpacking:

places = ("beach", "house", "school")
print(places) # ("beach", "house", "school")

(a, b, c) = places
print(a) # beach
print(b) # house
print(c) # school

Dictionaries

The last way to store multiple data in a variable is with a dictionary. Dictionaries are written with curly brackets (there are keys and values), are ordered, changeable, and does not allow duplicates. To get the length of a dictionary use the len function. Each entry in a dictionary has a key and a value. The key is used as an id for the value in a dictionary. When indexing a dictionary, index with the id. Here is an example of a dictionary:

computer = {
    "year": 2021,
    "model": "ABC123",
    "color": "gray"
    }
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray"}

print(computer["model"]) # ABC123

Note how there is a colon between each key and value. Ex: key: value.

Notice how when defining the dictionary computer, it is multiline. This is only a stylistic choice used to easily differentiate all the keys and values.

To add to the dictionary it is very similar to adding to a list. Reference the new key and set it equal to the value. Ex: dictionary[key] = value. To add items to a dictionary you can also use the update function. If you add or update an existing key, it replaces it. To remove an item use the pop method indexing the key. You can also use the popitem function to remove the last item in the dictionary. To clear the dictionary, use the clear function. Here are some examples:

computer = {
    "year": 2021,
    "model": "ABC123",
    "color": "gray"
    }
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray"}

computer["cpu"] = "XYZ789"
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray", "cpu": "XYZ789"}

computer.update({"ram": 32})
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray", "cpu": "XYZ789", "ram": 32}

computer["cpu"] = "ZZZ999"
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray", "cpu": "ZZZ999", "ram": 32}

computer.pop("cpu")
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray", "ram": 32}

computer.popitem()
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray"}

computer.clear()
print(computer) # {}

To get the value of a key you can either use the index or the get function. To get keys, you can use the keys function to get a list of all the keys which is a "view" of the dictionary so any changes are reflexed in the list. To get values, you can use the values function to get a list of all the values which is a "mirrored" view of the dictionary so any changes are reflexed in the list. To get items, use the items function to get a list of each item as a tuple which is a "reflection" of the dictionary so any changes are reflexed in the list. Below is an example:

computer = {
    "year": 2021,
    "model": "ABC123",
    "color": "gray"
    }
print(computer) # {"year": 2021, "model": "ABC123", "color": "gray"}

print(computer["model"])     # ABC123
print(computer.get("model")) # ABC123

a = computer.keys()
computer["cpu"] = "XYZ789"
print(a) # dict_keys(["year", "model", "color", "cpu"])

b = computer.values()
computer["ram"] = 32
print(b) # dict_values([2021, "ABC123", "gray", "XYZ789", 32])

c = computer.items()
computer["fans"] = 5
print(c) # dict_items([("year", 2021), ("model", "ABC123"), ("color", "gray"), ("cpu", "XYZ789"), ("ram", 32), ("fans", 5)])

You can also nest dictionaries. You can have lists or even dictionaries inside of a dictionary. Below is an example of a dictionary inside a dictionary:

computer = {
    "date": {"day": 29, "month": "september", "year": 2021},
    "model": "ABC123",
    "color": "gray"
    }
print(computer) # {"date": {"day": 29, "month": "september", "year": 2021}, "model": "ABC123", "color": "gray"}

Connecting to conditionals

Now that we know more about storing multiple data as a variable let's see some applications of it. One application is with conditionals and the "in" statement. The "in" statement returns true if a is in b. Below is an example:

numbers = [1, 3, 20, 100, 202, 267]

if 100 in numbers:
    print("100 is in numbers")

In also applies to strings and is very useful. Here is an example:

a = "Programming is one of my favorite things to do"

if "favorite" in a:
    print("favorite is in a")

Connecting to Loops

Another application of storing multiple data is with loops. You can loop through different variables and the items they store. Here is an example that prints all the items in each of the variables:

numbers = [1, 3, 20, 100, 202, 267]
for num in numbers:
    print(num)

words = {"hello", "goodbye", "howdy"}
for word in words:
    print(word)

floats = (0.9, 0.1, 24.3, 100.001)
for flt in floats:
    print(flt)

dog = {
    "breed": "poodle",
    "age": 10,
    "weight": 100.5
}
for key in dog:
    print(dog[key])

Note that the dictionary looped through all the keys so the print statement used the keys to print the values.

❮ PreviousNext ❯