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, by organizing data in a hierarchical structure. Nested lists can be used to represent 2D arrays, tables, and other multi-dimensional data.
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 what nested lists are, how to create and manipulate them, and provide some examples to help you understand the concept easily.
Python Nested Lists: Everything You Need to Know
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 incredibly versatile and can be used to represent various data structures, such as grids, matrices, and hierarchical data.
Creating 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
Accessing 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 print(element) # Output: 'banana'
The first set of brackets (
) accesses the first sublist, and the second set (
) accesses the second element within that sublist.
Modifying 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 = 'kiwi' print(data) # Output: [['apple', 'kiwi', 'cherry'], [7, 11, 17], ['dog', 'cat', 'fish']]
Iterating Through Nested Lists
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.
The Best 5 Python Nested Lists Examples with Full Code
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:
1. Linearize a Nested List
Problem: In this problem, we’re given a deeply nested list of various items, including strings and sublists. Our aim 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.
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']
2. Transposing a Matrix
Problem: Given a matrix (a nested list of lists), write a Python program to transpose it, swapping rows and columns.
def transpose(mtx): tr = [[mtx[j][i] for j in range(len(mtx))] for i in range(len(mtx))] 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]
3. Finding the Sum of All Elements in a Nested List
Problem: Calculate the sum of all elements in a nested list, which may contain both numbers and other lists.
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
4. Finding the Maximum Value in a Nested List
Problem: Find the maximum value within a nested list using Python that may contain both numbers and other lists.
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
5. Checking for the Presence of an Element
Problem: Determine whether a specific element exists in a nested list.
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.
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.