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.
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.