Getting list shape in Python
In Python, knowing the shape of a list is very important for working with data structures, especially when it comes to multidimensional or nested lists. This article explores various ways to determine the shape of a list in Python, from simple one-dimensional lists to complex multidimensional or irregularly nested lists.
Using len()
a function to get the shape of a 1D list in Python
The easiest way to get the shape of a list in Python is to use len()
the function . It gives you the length (number of elements) of the list, effectively giving you the size of the first dimension.
len()
Functions have a simple and concise syntax:
len(object)
object
is the object whose length you want to determine. It can be a sequence (such as a list, tuple, or string) or a collection (such as a dictionary or set).
The following code example demonstrates how to use len()
methods to get the shape of a list in Python.
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length of the list:", length)
Output:
Length of the list: 5
In this example, my_list
the length of the list is calculated and printed to the console.
Using list comprehensions and len()
functions to get the shape of a nested list in Python
In addition to determining the length of a flat (1D) list, we can also use len()
functions to determine the shape of nested lists (2D or higher dimensional lists).
In the following example, we determine the number of rows and columns in a 2D nested list.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
num_rows = len(nested_list)
# Assuming all sublists have the same number of columns
num_cols = len(nested_list[0])
print(f"Number of rows: {num_rows}, Number of columns: {num_cols}")
Output:
Number of rows: 3, Number of columns: 3
Here, num_rows
represents the number of rows (number of sublists) and num_cols
represents the number of columns (number of elements) of each sublist in the nested list.
Getting the shape of a multidimensional list in Python using NumPy
If we want our code to be able to work with any multidimensional lists, we can use NumPy's shape
attribute . It returns a tuple containing the number of elements in each dimension of the array.
The NumPy package was originally designed to work with arrays, but can also be used with lists. NumPy is an external package and is not pre-installed in Python, so we need to install it before using it.
The command to install the NumPy package is as follows.
pip install numpy
The following code example shows how to get the shape of a multidimensional list using NumPy.
import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6]])
num_rows, num_cols = my_array.shape
print(f"Number of rows: {num_rows}, Number of columns: {num_cols}")
Output:
Number of rows: 2, Number of columns: 3
Here, a NumPy array is created my_array
and then shape
its shape is retrieved using the shape attribute. This method works for multidimensional arrays, providing the number of rows and columns.
Using recursion to get the shape of an irregular nested list in Python
In some cases, we may encounter irregularly nested lists where the nesting depth varies and the sublists have different lengths. To handle such situations, we can use a recursive function.
def get_shape(data):
if isinstance(data, list):
return [len(data)] + get_shape(data[0])
else:
return [] # Assuming leaf elements are considered as a single column
nested_list = [[1, 2], [3, 4, 5], [6, [7, 8]]]
shape = get_shape(nested_list)
num_rows, num_cols = shape
print(f"Number of rows: {num_rows}, Number of columns: {num_cols}")
Output:
Number of rows: 3, Number of columns: 2
get_shape()
The function works by recursively traversing the nested list, counting the number of rows in each dimension and assuming that leaf elements are treated as single columns. This approach can provide the number of rows and columns for irregularly nested lists.
in conclusion
The most straightforward way to get the shape of a one-dimensional list in Python is to use len()
a function. For nested lists, list comprehensions along with len()
functions can help determine the number of rows and columns efficiently.
For more advanced scenarios involving multidimensional arrays, NumPy shape
attributes provide a convenient way to get the number of rows and columns. Finally, when dealing with irregularly nested lists of varying depths and lengths, recursive functions can be used to accurately determine the shape.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Finding a string in a list in Python
Publish Date:2025/05/09 Views:75 Category:Python
-
This tutorial shows you how to find elements from a Python list that have a specific substring in them. We will use the following list and extract ack the strings that have in it. my_list = [ "Jack" , "Mack" , "Jay" , "Mark" ] for Find elem
How to Find the Maximum Value in a List in Python
Publish Date:2025/05/09 Views:99 Category:Python
-
This tutorial will demonstrate how to find the maximum value in a list in Python. This tutorial will cover a number of scenarios and data types, from simple lists of integers to more complex structures like arrays within arrays. for Finding
Convert a list to a set in Python
Publish Date:2025/05/08 Views:145 Category:Python
-
This tutorial demonstrates how to convert a list to a set in Python. Difference between List and Set Lists and sets are standard Python data types that store values in sequence. Python list stores comma separated values between
Remove the first element from a list in Python
Publish Date:2025/05/08 Views:173 Category:Python
-
This tutorial will discuss different ways on how to remove the first element from a list. pop() Remove the first element from a list using the pop() Method can remove an element from a specific index. We have to specify the index from which
Convert a list to lowercase in Python
Publish Date:2025/05/08 Views:112 Category:Python
-
Lists can be used to store multiple items in a single variable. In Python, we can create a list of strings by enclosing the different elements in the list in single or double quotes. This tutorial demonstrates how to convert a list of strin
Remove all occurrences of an element from a Python list
Publish Date:2025/05/08 Views:69 Category:Python
-
In Python, lists allow the same element to appear multiple times. Even though the value of an element may be the same as other elements, each element will have a different index. Using these index numbers, you can easily access any element
Convert hex to bytes in Python
Publish Date:2025/05/08 Views:102 Category:Python
-
Hexadecimal, often abbreviated to hex, uses 16 symbols (0-9, a-f) to represent values, in contrast to the decimal system's 10. For example, 1000 in decimal is 3E8 in hexadecimal. Being proficient in dealing with hexadecimal is essential for
b in front of string in Python
Publish Date:2025/05/08 Views:54 Category:Python
-
This tutorial will discuss the statement in Python b" . b" Using the statement in Python b" The notation is used to specify strings in Python bytes . In contrast to regular strings with ASCII characters, bytes a string is an array of byte v
How to Convert Integer to Binary in Python
Publish Date:2025/05/08 Views:130 Category:Python
-
This tutorial explains how to convert an integer to binary in Python. This tutorial also lists some sample codes to illustrate different ways of converting from int to binary in Python. bin() Convert Int to Binary in Python using In Python,