TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Find the List Shape in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

How to Find the List Shape in Python

Last updated: Feb 05, 2024 12:55 am
By Soumya Agarwal
Share
6 Min Read
How to Get the List Shape in Python
SHARE

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. Let’s dive into the methods available to achieve this in Python with some good examples.

Contents
Method 1: Using len() for 1D ListsMethod 2: Using len() for 2D Lists Shape in PythonMethod 3: Using NumPy for Multi-Dimensional ArraysMethod 4: Handling Irregular 2D Lists Shape in PythonMethod 5: Using ndim for NumPy Arrays

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.

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 Lists

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 Lists Shape in Python

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: Using NumPy for Multi-Dimensional Arrays

If you’re working with multi-dimensional arrays, the 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: Handling Irregular 2D Lists Shape in Python

In scenarios where the inner lists may have different lengths, you need to account for the maximum length to accurately represent the shape. 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

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:

import numpy as np

# Create a 3D NumPy 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 NumPy array is: {array_dimensions}")

In this example, the array has three dimensions, so the result will be 3.

Conclusion

Great job! 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.

Keep Coding Happily,
Team TechBeamers.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Soumya Agarwal Avatar
By Soumya Agarwal
Follow:
I'm a BTech graduate from IIITM Gwalior. I have been actively working with large MNCs like ZS and Amazon. My development skills include Android and Python programming, while I keep learning new technologies like data science, AI, and LLMs. I have authored many articles and published them online. I frequently write on Python programming, Android, and popular tech topics. I wish my tutorials are new and useful for you.
Previous Article Pandas Get Average Of Column Or Mean in Python Pandas Get Average Of Column Or Mean in Python
Next Article Python Script To Generate Test Cases for Java Classes How to Use Python To Generate Test Cases for Java Classes

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x