Skip to content

Collections and Loops

Are used throughout the project: - a list of project records returned from /projects - dictionaries representing incoming JSON payloads - sets when we want unique status or priority values - tuples to define fixed values to bundle together

Python has a few different types of data types for storing and organizing data.

  • lists
  • tuples
  • sets
  • dictionaries

Lists

A list is an ordered collection of values. Lists are useful when you care about order and want to add, remove, or change items.

Python
project_names = ["Payments API", "Developer Portal", "Ops Console"]
project_names.append("Marketing Site")
print(project_names)

Use lists for things like:

  • a list of projects returned by an API
  • a list of tasks to filter
  • a list of names to sort

It's not best practice, but lists don't have to contain the same types.

Tuples

A tuple is also ordered, but it is immutable (values can't be modified after creation, items can't be added or removed).

Python
version = ("alpha", 0.1)
Tuples are useful for coordinates, pairs, and other small records.

Sets

A set stores unordered unique values.

Python
unique_priorities = {"low", "medium", "high", "urgent", "high"}
print(unique_priorities)

Use a set when the values are distinct, and you don't care about storing duplicates.

You can also perform set operations on the values.

Dictionaries

A dictionary maps keys to values.

Python
project = {
    "name": "Payments API",
    "archived": False,
}

Dictionaries are one of the most important Python data structures because JSON objects look very similar to them. That makes dictionaries a natural fit for API-shaped data.

Collections Examples

Python
project_names = ["Payments API", "Developer Portal", "Ops Console"]
status_pair = ("planned", "in_progress")
unique_priorities = {"low", "medium", "high", "urgent"}
project = {"name": "Payments API", "archived": False}

Lists and Strings

Python REPL
# get the length of a string
>>> name = "Nina"
>>> len(name)
4

# split, defaults to space
# returns a list back
>>> letters = "A B C D E"
>>> letters.split()
['A', 'B', 'C', 'D', 'E']

>>> csv_values.split(",")
['date', 'name', 'sum']

# join, returns a string with a delimiter when passed a list
>>> " ".join(["Nina", "Fitz", "Seven"])
'Nina Fitz Seven'

Lists and strings work together often. For example, I might split a name into parts, clean each part, and then join them back together.

Be mindful of which methods modify your collection, and which methods return a new value.

Python REPL
# Sorting by calling .sort() or .reverse() on a list modifies the list
>>> names = ["Nina", "Fitz", "Seven"]
>>> names.sort()
>>> names
['Fitz', 'Nina', 'Seven']
>>> names.reverse()
>>> names
['Seven', 'Nina', 'Fitz']

# Calling sorted returns a new list that's sorted, but doesn't modify the original
>>> names = ["Nina", "Fitz", "Seven"]
>>> sorted(names)
['Fitz', 'Nina', 'Seven']
>>> names
['Nina', 'Fitz', 'Seven']

These types can be combined, for example a dictionary can contain lists for values. Dictionary keys need to be hashable, meaning an immutable type.

Python
person = {"name": "Nina", "fav_foods": ["Japanese", "Italian"]}

Because tuples are immutable they can also be used as dictionary keys.

Python
stuff = ["Red", 1.0, True]
other_stuff = ("blue", 3, False)

A list is mutable, meaning its values can be changed. A tuple is immutable, meaning it's values can't be changed. Tuples are faster and more memory efficient, and can be used for dictionary keys because of their immutability.

Python
stuff.append(42)
print(stuff)
# ['Red', 1.0, True, 42]

other_stuff.append(42)
# AttributeError: 'tuple' object has no attribute 'append'

Loops

Looping over these types:

Python
fruits = ["Apple", "Kiwi", "Mango"]
for fruit in fruits:
    print(fruit)

statuses = ("started", "in progress", "done")
for status in statuses:
    print(status)

unique_numbers = {1, 2, 3}
for number in unique_numbers:
    print(number)

person = {
    "name": "Nina",
    "num_pets": 1,
}

# use person.keys() for just keys
# use person.values() for just values
for key, value in person.items():
    print(key, value)

Here is a list of dictionaries like the kind I normalize before building more structure:

Python
raw_tasks = [
    {"title": " ship docs ", "priority": "High", "done": False},
    {"title": "cut release", "priority": " urgent ", "done": 0},
    {"title": "announce launch", "priority": "MEDIUM", "done": 1},
]

Keep in mind

  • lists preserve order and can be changed
  • tuples preserve order and work well for fixed-size records
  • sets remove duplicates
  • dictionaries map names to values and are the most common shape for JSON-like data