Welcome to this short tutorial where we’ll explore how to get the list shape in Python. This knowledge becomes essential when working with multi-dimensional data structures, like lists of lists a.k.a. nested lists or NumPy arrays.
Understand About the List Shape in Python
Let’s dive into the methods available to achieve this in Python with some good examples. But, first, understand the concept of a list shape.
What Does a List Shape Mean in Python?
In Python, the shape of a list refers to its dimensions or structure. For one-dimensional lists, the shape is simply the number of elements, while for multi-dimensional lists, it includes the size of each dimension.
Imagine a list as a shopping cart where you can store various items. You can have fruits, vegetables, snacks – all sorts of things! Similarly, in Python, a list can hold different data types like numbers, strings, or even other lists. But unlike your shopping cart, a list has a definite size, telling you how many items it contains.
Simple Python Methods to Get List Shape
Hopefully, you now have a fair idea of what a list shape means in Python. So, the next step is to learn how to get the shape of a list, which we’ll explore in the following section.
Method 1: Using len() for 1D List Shape
For a one-dimensional list, the built-in len()
function provides the number of elements. Let’s see an example:
# Create a one-dimensional list with decimal values
grades = [95.5, 87.3, 92.1, 78.9, 88.6]
# Get the shape using len()
list_shape = len(grades)
# Display the result
print(f"The shape of the list is: {list_shape}")
In this example, the list has five elements, so the shape will be 5.
Method 2: Using len() for 2D List Shape
When dealing with a two-dimensional list, using len()
gives the number of rows. To get both the number of rows and columns, consider the length of each inner list:
# Create a two-dimensional list with alphanumeric strings
matrix = [
['apple', 'orange', 'banana'],
['dog', 'cat', 'bird'],
['red', 'blue', 'green']
]
# Get the total no of rows
rows = len(matrix)
# Get the total no of columns (say, all rows are of same size)
columns = len(matrix[0])
# Display the result
print(f"The shape of the 2D list is: ({rows}, {columns})")
In this case, the list has 3 rows and 3 columns, so the shape will be (3, 3).
Method 3: NumPy for Multi-Dim Arrays
If you’re working with multi-dimensional arrays or so to say a list, Python’s NumPy library provides a convenient way to get the shape. First, make sure to install NumPy by running:
pip install numpy
Now, let’s see how to use NumPy to get the shape of a multi-dimensional array:
import numpy as np
# Create a 2D NumPy array with decimal values
np_array = np.array([[2.5, 4.3, 6.1],
[8.7, 10.2, 12.8],
[14.3, 16.9, 18.5]])
# Get the shape using shape attribute
array_shape = np_array.shape
# Display the result
print(f"The shape of the NumPy array is: {array_shape}")
In this example, the shape of the NumPy array will be returned as a tuple (3, 3), indicating 3 rows and 3 columns.
Method 4: Handle Irregular 2D Lists
In scenarios where the inner lists may have different lengths. We commonly call these irregular list shapes in Python. To handle these cases, you must consider the maximum length to represent them accurately. To illustrate, let’s modify the previous example:
# Create an irregular 2D list with decimal values
irregular_matrix = [
[1.2, 2.4, 3.6],
[4.8, 5.1],
[6.3, 7.5, 8.7, 9.9]
]
# Get the number of rows
rows_irregular = len(irregular_matrix)
# Get the number of columns (considering the maximum length of inner lists)
columns_irregular = max(len(row) for row in irregular_matrix)
# Display the result
print(f"The shape of the irregular 2D list is: ({rows_irregular}, {columns_irregular})")
Here, the shape is (3, 4) since the third inner list has four elements.
Method 5: Using Ndim for NumPy Arrays
Python’s NumPy provides the ndim
attribute to determine the number of dimensions in an array. This is particularly useful for arrays with more than two dimensions. Consider the following Python code.
import numpy as np
# Create a 3D array with alphanumeric strings
np_3d_array = np.array([[['apple', 'orange', 'banana'], ['dog', 'cat', 'bird']],
[['red', 'blue', 'green'], ['yellow', 'purple', 'pink']]])
# Get the number of dimensions using ndim
array_dimensions = np_3d_array.ndim
# Display the result
print(f"The number of dimensions in the 3D array is: {array_dimensions}")
In this example, the array has three dimensions, so the result will be 3.
Before You Leave
Today, you’ve learned various ways to find the shape of a list in Python. This is useful, especially when dealing with more complicated data. As you continue with Python, understanding your data’s shape will help a lot in tasks like scientific computing, data analysis, and machine learning.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.