Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Data Structures

To analyze census data, we need more than just simple variables. We need Containers to hold collections of data.

Source: Python 3 Documentation: Data Structures

Lists

Think of a list as a n array of items stored in sequential order. Lists are identified/created using square brackets [ ].

Lists are:

  • Ordered: the items have a defined order, and that order will not change

  • Mutable: they can be modified (change, add, remove items) after they are created

  • Allows duplicates: list items can have the same value

A list can contain objects of different data types (int, float, char, list). In fact, a list can contain other lists. This list within a list is known as a nested list.

Output

Accessing list items/elements

List items are accessed using their index. The first item on the list always has an index of 0.

Output
'Palay'

A negative index (e.g. -1, -2) means to start from the end. -1 refers to the last item.

Output
'Coconut'

You can also get a range of values by specifying a range of indexes of where to start and where to end the range.

Output
['Corn', 'Coconut']

Accessing items in nested lists

Output
'a'

Modifying lists

Since lists are mutable, we can update the data.

Output
['Palay', 'Yellow Corn', 'Coconut', 'Mango']

Removing items in a list

  • remove(): removes the first occurance of an item

  • pop(): removes the specified index

Output
['Palay', 'Corn', 'Coconut']
Output
['Palay', 'Corn']

Sort list items

  • sort(): sort list alphanumerically, by default

Output
['Coconut', 'Corn', 'Mango', 'Palay']

NOTICE THAT THE LIST IS EDITED IN PLACE

Joining lists

  • +

  • append(): appending all the items from one list to another using a for loop

  • extend(): add elements from one list to another list

Output
['Palay', 'Corn', 'Coconut', 'Mango', 'Eggplant', 'Ampalaya']
Output
['Palay', 'Corn', 'Coconut', 'Mango', 'Eggplant', 'Ampalaya']

NOTICE THAT LIST1 IS EDITED

Output
['Palay', 'Corn', 'Coconut', 'Mango', 'Eggplant', 'Ampalaya']

NOTICE THAT LIST1 IS EDITED

Looping lists and list comprehensions

Output
Palay
Corn
Coconut
Mango
Output
Palay
Corn
Coconut
Mango
[None, None, None, None]

CHALLENGE 01

How do you change a range of values for a list?

Tuples

Tuples are immutable lists—meaning they cannot be modified once created. Items in a tuple can be accessed similar to that of lists. A tuple is identified/created using a parenthesis ( ).

Tuples are:

  • Ordered: the items have a defined order, and that order will not change

  • Immutable: they cannot be modified after they are created

  • Allows duplicates: tuple items can have the same value

You can convert between tuples in lists using the tuple and list functions.

Why use tuples instead of lists? They are more efficient than lists so it’s best to use them for data that we know won’t change.

Output
('Palay', 'Corn', 'Coconut', 'Mango')

Unpacking a tuple

Output
Palay

Sets

Sets are:

  • Unordered: the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

  • Immutable: they cannot be modified after they are created

  • Unique/Does not allow duplicates: sets cannot have two items with the same value

Sets are an easy way to get unique values from a list.

Output
Original List: [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 9, 1, 5, 10, 11, 12, 6, 13, 14, 15, 7, 16, 17, 18, 9, 19, 20]
Set without Duplicates: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
Output
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}
Output
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}

Dictionaries (dicts)

  • Dictionaries are used to store data values in key:value pairs.

  • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

  • Dicts consist of a set of keys and values that provide the ability to perform and indexed lookup.

  • Dictionaries are identified/created using curly brackets { }.

Dicts are:

  • Mutable: they can be modified after they are created

  • Does not allow duplicate keys: dicts cannot have two items with the same key

Output
Output
'Juan Dela Cruz'

Dictionaries can also be created using the dict function.

Output
{'farm_id': 'F-10203', 'operator': 'Juan Dela Cruz'}

Accessing items

Dict items are accessed using their keys

Output
Juan Dela Cruz
Output
Juan Dela Cruz

Get keys and values

  • keys(): gets keys

  • values(): gets values

Output
dict_keys(['farm_id', 'operator'])
Output
dict_values(['F-10203', 'Juan Dela Cruz'])

CHALLENGE 02

How would you iterate over the items in a dictionary?

You can check to see if a dict contains a certain key or value:

Output
True
True
Output
False

Try to access an non-existent key (e.g.‘palay’):

Output
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[31], line 1
----> 1 farm_record['palay']

KeyError: 'palay'

You can check if a value exists before accessing it:

Output
F-10203

You can also wrap the code block in a try/except bloc (more preferred and Pythonic way).

Output
Key not found