Popular Posts

Friday, August 28, 2020

Python Beginner: 2D Lists & Nested Loops

 Hello, Developer!


Today, we will learn "2D Lists" and "Nested Loops".

Let's look into 2D Lists first. We can simply tell the 2 dimensional(2D) Lists are grids or arrays which consist of rows and columns. Here are some examples of 2D Lists.


Examples of 2 & 3 dimensional(2D & 3D) Lists 

list_2D_1 = [ [a, b, c], [d, e, f], [g, h, i]]

list_2D_2 = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]

list_3D_1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]


Example of Calling values from 2D & 3D Lists

list_2D([row index 1][column index 2]) # Example: list_2D_1([0] [0]) = a, list_2D_1([0] [1]) = b, list_2D_1([2] [2]) = 8

list_3D([1st index][2nd index][3rd index]0 # Example: list_3D_1([0][0][0]])=1, list_3D_1([1][1][0]])=7


Similar way, Nested loops can be used to calling values from multi dimension(2D, 3D or higher dimension) lists. Here are normal loop and nested loop examples for understanding through comparing of each loop process.


Normal Loop calling values from Multi-dimension Lists example

for value in multi-dimension list:

      print(value) # In this case, you will call value by list type like [a,b,c] or [1,2,3]


Nested Loop calling values from Multi-dimension List example

for value_1 in multi-dimension list:

      for value_2 in value_1 # In this case, you will call value by individual values type like a, b, c,... or 1, 2, 3... 

 

Here, I showed full exercise codes and execution result as following.

number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
print(number_grid[0][1])

list_2D_2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list_2D_2)
print(list_2D_2[0][0])

list_3D_1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
print(list_3D_1[0][1][1])


for row in number_grid:
print(row) # If you want to print out all values in list as list type like [1,2,3],[[4,5,6],...

for row in number_grid:
for col in row: # If you want to print out all values as individual values as 1,2,3...
print(col)


Can you see the same result in your PC and your coding? Great job! Now you can use "Multi Dimension Lists" and "Nested Loops" in your Python program.


Alright, see you on next post! 😊 

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...