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 Use Nested Lists in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • 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 ExamplesPython Tutorials

How to Use Nested Lists in Python

Last updated: Jun 02, 2024 5:52 pm
By Harsh S.
Share
8 Min Read
Python Nested Lists with Examples
SHARE

In Python, a nested list is a list that contains other lists as its elements. This concept allows you to create more complex data structures, like tables or matrices. Nested lists can be used in programs to represent 2D arrays, tables, and other multi-dimensional data.

Contents
Create Nested ListsAccesse Elements in Nested ListsModify Nested ListsIterate Through Nested ListsCommon Use CasesNested Lists Examples in Pythoni) Linearize a Nested Listii) Transposing a Matrixiii) Finding the Sum of All Elements in a Nested Listiv) Finding the Maximum Value in a Nested Listv) Checking for the Presence of an ElementA Quick Wrap

The concept of nested lists, where a list can contain other lists, naturally evolved as Python developers needed to represent and manipulate multi-dimensional data.

In this tutorial, we’ll explore how to create nested lists, use them, and provide some examples to help you understand the concept easily.

Try Yourself: The Best 30 Questions on Python List, Tuple, and Dictionary

Introduction to Nested Lists

A nested list is a list that can contain other lists as its elements. This nesting can go to any depth, meaning you can have lists within lists within lists, and so on. Nested lists are versatile and represent various data structures, such as grids, matrices, and hierarchical data.

Create Nested Lists

Creating a nested list in Python is straightforward. You can define a list and include other lists as its elements. Here’s an example:

data = [['apple', 'banana', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]

In this example, the data contains three sublists, each of which contains a mix of strings and numbers.

Must Read: Your Ultimate Guide to Python List Slicing

Accesse Elements in Nested Lists

To access elements in a nested list, you do it via indexing in your Python code. Each level of nesting requires a set of square brackets to access the elements.

data = [['apple', 'banana', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]

# Accessing the second element in the first sublist
element = data[0][1]
print(element)  # Output: 'banana'

The first set of brackets ([0]) accesses the first sublist, and the second set ([1]) accesses the second element within that sublist.

Modify Nested Lists

You can modify elements in a nested list just like you would with a regular list. Use indexing to access the element you want to change and then assign a new value.

data = [['apple', 'banana', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]

# Changing the value at the first row, second column
data[0][1] = 'kiwi'
print(data)
# Output: [['apple', 'kiwi', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]

Iterate Through Nested Lists

You can use a Python for loop to iterate through the elements of a nested list. Here’s an example using a nested for loop:

data = [['apple', 'banana', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]

for n in data:
    for ix in n:
        print(ix)

This code will print all the elements in the data list, including both strings and numbers.

Common Use Cases

Nested lists are used in various scenarios, such as:

  • Representing grids and matrices.
  • Storing tabular data where each row is a sublist and each column is an element within that sublist.
  • Hierarchical data structures, like trees or organizational charts.

Nested Lists Examples in Python

Here’s a list of the best 5 Python nested list problems along with their descriptions and example code to help you understand and solve them:

i) Linearize a Nested List

Problem: You have a deep nested list of items, including strings and sublists. Your task is to turn this intricate structure into one list that includes all the elements in the nested list. This process effectively linearizes the nested structure into a single list.

Python code:

def linearize(nested):
    linear = []
    for ix in nested:
        if isinstance(ix, list):
            # If the item is a list, recursively call the function
            # to linearize it further and extend the linear list.
            linear.extend(linearize(ix))
        else:
            # If the item is not a list, add it directly to the linear list.
            linear.append(ix)
    return linear

nested = ['apple', ['banana', 'cherry'], 'grape', ['kiwi', ['lemon', 'orange']]]
result = linearize(nested)
print(result)

# Result
# ['apple', 'banana', 'cherry', 'grape', 'kiwi', 'lemon', 'orange']

ii) Transposing a Matrix

Problem: Given a matrix (a nested list of lists), write a Python program to transpose it, swapping rows and columns.

Python code:

def transpose(mtx):
    tr = [[mtx[j][i] for j in range(len(mtx))] for i in range(len(mtx[0]))]
    return tr

mtx = [[2, 7, 17], [3, 11, 19], [5, 13, 23]]
tr = transpose(mtx)

for r in tr:
    print(r)

# Result
# [2, 3, 5]
# [7, 11, 13]
# [17, 19, 23]

iii) Finding the Sum of All Elements in a Nested List

Problem: Calculate the sum of all elements in a nested list, which may contain numbers and other lists.

Python code:

def sum_nested(nested_list):
    total = 0
    for ix in nested_list:
        if isinstance(ix, list):
            total += sum_nested(ix)
        elif isinstance(ix, int):
            total += ix
    return total

data = [2, 3, [5, 7], [11, ['thirteen', 17]]]
result = sum_nested(data)
print(result)  # Output: 45

Also Check: Python List All Files in a Directory

iv) Finding the Maximum Value in a Nested List

Problem: Find the maximum value within a nested list using Python containing numbers and other lists.

Python code:

def find_max_nested(nested_list):
    max_val = float('-inf')
    for ix in nested_list:
        if isinstance(ix, list):
            max_val = max(max_val, find_max_nested(ix))
        else:
            if isinstance(ix, int) and ix > max_val:
                max_val = ix
    return max_val

data = [2, 3, [5, 7], [11, ['thirteen', 17]]]
result = find_max_nested(data)
print(result)  # Output: 17

v) Checking for the Presence of an Element

Problem: Determine whether a specific element exists in a nested list.

Python code:

def element_exists(nested_list, target):
    for ix in nested_list:
        if isinstance(ix, list):
            if element_exists(ix, target):
                return True
        else:
            if ix == target:
                return True
    return False

data = [1, [2, 'apple'], [3, [4, 'banana', 5]]]
target = 'banana'
result = element_exists(data, target)
print(result)  # Output: True

These are common problems involving nested lists in Python, along with example code solutions. Understanding how to work with nested lists is crucial for dealing with complex data structures and solving various programming challenges.

Check This: Python Program to Convert Lists into a Dictionary

A Quick Wrap

Nested lists in Python are not limited to a fixed number of dimensions, and you can nest lists as deeply as needed to represent the structure of your data.

Python’s nested lists provide a flexible way to work with multi-dimensional data. With the knowledge you’ve gained in this tutorial, you should be well-equipped to create, access, and manipulate nested lists in your Python programs. Whether you’re working with tables, grids, or any other structured data, nested lists can be a powerful tool in your programming toolkit.

Lastly, our site needs your support to remain free. Share this post on social media (Facebook/Twitter) if you gained some knowledge from this tutorial.

Happy coding,
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

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Python List Slicing with Examples Your Ultimate Guide to Python List Slicing
Next Article Python Generate All Subarrays of an Array Generate All Subarrays of an Array in Python

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