Two Dimensional Lists In Python

This page is on two dimensional lists in Python.


Two Dimensional Lists

In a one dimensional list, the elements are single values. With a two dimensional list, the elements are lists. You can have lists within a list.



In one dimensional arrays, indexing can be done with square brackets and a number. Each element in a two dimensional array is a list. To access the elements in a list within the list, a second set of square brackets is needed.


In the first example, having just [0] after brother_sister will select the first list of Tom and Kate.


To access Tom from the first list a second [0] is needed. The brother_sister[0][0] part means to select the first list and then first element within this list.


Having brother_sister[0][1] will obtain the first list and then the second element from the first list. This is Kate.


The last list within the last has an index of 3. To obtain the name Cara, select the list of index 3 with the second index as 1.


For Loops With 2-D Lists

In a for loop, you can access each list in a 2-D array with one for loop. To access through each element through all of the lists, a second for loop is required inside the first for loop.

This first example showcases a for loop through the brother_sister list. Each list is printed.


When it comes to adding in a second for loop inside the first for loop, be careful with the variables. In the second for loop, I loop through each list to access each element.



Converting A 2-D List Into A 1-D List

With the use of a double for loop, you can convert a two dimensional list into a one dimensional list. The contents from each list will be elements under one list.




Leave a Reply