Python is a powerful, high-level, object-oriented programming language. One of its most notable attributes is its readability. With a clean and straightforward syntax, Python has a low learning curve and ease of understanding.
In Python, a two-dimensional (2D) array is an array inside an array. It is bound to come in handy when dealing with large datasets, helping store data more compactly and keeping the logic of the program clear.
In this tutorial, we will focus on how to get the number of rows in a 2D array (also known as a list in Python). It is an essential part of managing and manipulating data in Python since it gives you an idea about the size of the dataset you’re dealing with.
Step 1: Create a 2D array
Let’s start by creating a simple 2D array. In Python, it’s called a list of lists. See the code below:
1 |
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
Step 2: Use the len function
After creating the 2D array, we can get the number of rows by using the len() function. The len() function in Python is used to get the length (number of elements) of a list.
1 |
num_rows = len(list_2d) |
Note: len() function with a list parameter returns its length which is equivalent to the number of rows.
Step 3: Print the Result
To confirm the result of our operation, we should print the num_rows variable:
1 |
print("Number of rows: ", num_rows) |
Following the above steps, the full code is as below:
Full Python Code
1 2 3 |
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] num_rows = len(list_2d) print("Number of rows: ", num_rows) |
When you run this code, your output should show:
Number of rows: 3
Conclusion
That’s it! Now you know how to get the number of rows in a 2D array in Python using the len() function. Although getting the number of rows in a 2D list seems to be a simple task, it plays a crucial role in managing complex data structures.
Remember that Python’s readability and simplicity allow you to quickly manipulate data and perform basic—but essential—operations on data structures such as arrays.