Welcome to today's session on "Multidimensional Arrays and Their Traversal in Python ". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. Picture it as an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in Python.
To construct a multidimensional or nested array in Python, we use lists inside lists. Here's an example of a 2-dimensional array:
In this example, array is a 2-dimensional array, just like a 3-storey 'apartment building,' where every floor is an inner list.
All indices in Python arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building. Here's how you can do it:
We visited the element 4 in the array by its position. The number 1 inside the first square brackets refers to the second inner list, and 0 refers to the first element of that list.
Continuing with the apartment-building analogy, suppose the task was to replace the old locker code (the second element in the first list) with a new one. Here's how we can achieve this:
Python offers a variety of built-in methods that are handy with multidimensional arrays:
- len(Array): It's like asking how many floors are there in our 'apartment building'. It gives us the number of rows in an array:
- append(Element): With
append(), we can add a new floor and units on that floor to our 'apartment building'.
- remove(Element): Use remove() to get rid of an apartment (element) from a specific floor.
