Arrays

 An array is like a collection of items, and each item is of the same type. You can think of a 1D array like a list and a 2D array like a table. 

1D Arrays

Creating a 1D Array: Let's imagine you have a collection of action figures, and you want to remember all their names. You can use a 1D array to store these names. Here's how you would do that in Python:


action_figures = ["Spiderman", "Ironman", "Batman", "Superman"]


Accessing Elements in a 1D Array: You can access any action figure's name by referring to its position (or index) in the array. In Python, the index starts at 0, so Spiderman is at index 0, Ironman is at index 1, and so on. Here's how you can access "Batman":


print(action_figures[2])  # this will print "Batman"


Changing Elements in a 1D Array: What if you got a new action figure and wanted to replace "Batman" with "Hulk"? You can change an element in the array like this:


action_figures[2] = "Hulk"  # this changes "Batman" to "Hulk"


Iterating through a 1D Array: If you want to go through all the names in your array, you can use a loop. Here's how you can print out all the names:


for figure in action_figures:

    print(figure)


2D Arrays

Now, let's imagine you not only want to remember the names of your action figures, but also their colours. You can think of a 2D array like a table, where the first column is the name and the second column is the colour. 


Creating a 2D Array: Here's how you can create this table (or 2D array) in Python:


action_figures = [["Spiderman", "Red"], ["Ironman", "Gold"], ["Hulk", "Green"], ["Superman", "Blue"]]


Accessing Elements in a 2D Array: You can access the colour of any action figure by using two indices - the first for the row and the second for the column. So, to get "Hulk"'s colour:


print(action_figures[2][1])  # this will print "Green"


Changing Elements in a 2D Array: Let's say you got a new Hulk figure and it's not Green, but Purple. You can change the colour in the 2D array like this:


action_figures[2][1] = "Purple"  # this changes Hulk's colour from "Green" to "Purple"


Iterating through a 2D Array: If you want to go through all the figures and print out their names and colours, you can use a nested loop (a loop inside a loop). Here's how:


for figure in action_figures:

    for detail in figure:

        print(detail)


This will print out all the names and colours, one by one. If you want them in pairs (name and colour together), you can print them inside the first loop like this:


for figure in action_figures:

    print(f"Name: {figure[0]}, Colour: {figure[1]}")


0 Comments