Another Dimension

Recall the Boards lab. To create a computer-appropriate representation of the board, we used nested lists. This list of lists allowed for a more comprehensive representation of the board and let us view rows as a single list. Creating nested lists can be useful in other situations, like designing from user accounts or storing a graph.

A list within another list is called 2-Dimensional (2D). And just like in a 2D cartesian graph, retrieving an element requires two index values (essentially the x (row) and y (column) position).


>>> produce = ["kale", "spinach", "sprouts"]
>>> fruit = ["olives", "tomatoes", "avocado"]
>>> cart = [produce, fruit]
>>> cart
[ ["kale", "spinach", "sprouts"], ["olives", "tomatoes", "avocado"]]
        

The 0th and 1st list can be retrieved normally using the known notation. For example:


>>> cart[0]
["kale", "spinach", "sprouts"]
        

To access a deeper item (an item inside a nested list), simply add the second relevant index as demonstrated.


>>> cart[0][2]
'sprouts'
        

Hopefully this is relatively intuitive. The first index returns the internal list, and the second index then looks into that retrieved list. All of the previously mentioned list functions still operate on 2D lists:


>>> cart[0][2] = "cabbage"
>>> cart
[ ["kale", "spinach", "cabbage"], ["olives", "tomatoes", "avocado"]]
        

Exercise 2: Flatten List

Now that you have some experience with lists in Python, try writing a function that takes a list of lists (2D) and returns all the items of each list concatenated together into one new list. See below for an example.

Hint: To create an empty list, just set a variable equal to empty brackets, e.g. x = []


>>> flatten([["a", "b"],["c", "d", "e"], ["f"]])
["a", "b", "c", "d", "e", "f"]