Another Dimension

Recall the Lists 2: Tic Tac Toe Lab. To create a more computer-appropriate representation of the board, a list of winning triples was created. This list of lists allowed for a more comprehensive representation of the board. Creating nested lists can be useful when designing everything from user accounts to game boards.

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 and y 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, 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"]