Hướng dẫn nested list python

What is Python Nested List?

A list can contain any sort object, even another list [sublist], which in turn can contain sublists themselves, and so on. This is known as nested list.

Nội dung chính

  • What is Python Nested List?
  • Convert a list of lists to a flat list
  • How to Create a List of Lists in Python
  • What’s a List of Lists?
  • Memory Analysis
  • Create a List of Lists in Python
  • Convert List of Lists to One List
  • Python | Convert a nested list into a flat list
  • Nested List Comprehensions in Python
  • Video liên quan

You can use them to arrange data into hierarchical structures.

Convert a list of lists to a flat list

Suppose we have a list of lists i.e.

# List of list listOfList = [ [1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [17, 18, 19, 20, 21] ]
This list contains 3 different lists of integers. We want to convert this list of lists in to a single flat list, that should contain only integers like,
[1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
There are different ways to do this,

Use list comprehension to convert a list of lists to a flat list

We will use list comprehension to iterate over a lists of list and then for each internal list again iterate over the individual elements in that list. Then add those elements to a new list i.e.

# List of list listOfList = [ [1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [17, 18, 19, 20, 21] ] # Use list comprehension to convert a list of lists to a flat list flatList = [ item for elem in listOfList for item in elem] print['Flat List : ', flatList]
Output:
Flat List : [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
Although this is a single line solution but this kind of coding is not easy to maintain. So, let’s see some other options too,

Use list.extend[] to convert a list of lists to a flat list

In python list data type provides a method to add all the contents of an iterable to the existing list,

list.extend[iterable]
It extends the existing list object by appending all the contents of given iterable. Let’s use this to convert list of lists to a flat list,
# List of list listOfList = [ [1, 2, 3, 4, 5], [11, 22, 33, 44, 55], [17, 18, 19, 20, 21] ] flatList = [] for elem in listOfList: flatList.extend[elem] print['Flat List : ', flatList]
Output:
Flat List : [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
How did it worked ?

Advertisements

We created a new empty list. Then using for loop we iterated over the list of lists and then for each internal list appended its individual elements to our new flat list using list.extend[].

Well we achieved our result, but there is an another way to do this,

Use list.append[] to convert a list of lists to a flat list

In python list data type provides a method to add an item at the end of a list,

list.append[x]
Let’s use this to convert list of lists to a flat list,
flatList = [] for elem in listOfList: for item in elem: flatList.append[item] print['Flat List : ', flatList]
Output:
Flat List : [1, 2, 3, 4, 5, 11, 22, 33, 44, 55, 17, 18, 19, 20, 21]
How did it worked ?

We created a new empty list. Then using for loop we iterated over the list of lists, then for each internal list again iterated over the individual elements in that list. Then add those individual elements to a new list using list.append[]

All the above solution will work in case of list of lists. But what if we have nested list like list of numbers & lists. Also, internal lists might contain more lists. How to create a flat list from this kind of nested list ?

How to Create a List of Lists in Python

Last Updated: February 16th, 2022

This article is all about creating and initialize a list of lists in Python. A list of lists basically a nested list that contains one or more lists inside a list. There are many approaches to create a list of lists. Here, we are using the append[] method and list comprehension technique to create a list of lists. After creating a list of lists, we will see to access list elements as well. Let's see some examples.

What’s a List of Lists?

Definition: A list of lists in Python is a list object where each list element is a list by itself. Create a list of list in Python by using the square bracket notation to create a nested list [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon [Kindle/Print]!

Memory Analysis

It’s important that you understand that a list is only a series of references to memory locations. By playing with the code visualizer, you’ll gain a deeper understanding of how Python works at its core:

Simply click the “Next” button to see how each line of code unfolds.

Create a List of Lists in Python

Create a list of lists by using the square bracket notation. For example, to create a list of lists of integer values, use [[1, 2], [3, 4]]. Each list element of the outer list is a nested list itself.

Convert List of Lists to One List

Say, you want to convert a list of lists [[1, 2], [3, 4]] into a single list [1, 2, 3, 4]. How to achieve this? There are different options:

  • List comprehension [x for l in lst for x in l] assuming you have a list of lists lst.
  • Unpacking [*lst[0], *lst[1]] assuming you have a list of two lists lst.
  • Using the extend[] method of Python lists to extend all lists in the list of lists.

Find examples of all three methods in the following code snippet:

lst = [[1, 2], [3, 4]] # Method 1: List Comprehension flat_1 = [x for l in lst for x in l] # Method 2: Unpacking flat_2 = [*lst[0], *lst[1]] # Method 3: Extend Method flat_3 = [] for l in lst: flat_3.extend[l] ## Check results: print[flat_1] # [1, 2, 3, 4] print[flat_2] # [1, 2, 3, 4] print[flat_3] # [1, 2, 3, 4]

Due its simplicity and efficiency, the first list comprehension method is superior to the other two methods.

Python | Convert a nested list into a flat list

The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.

Examples:

Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]
Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]]
Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”]

Nested List Comprehensions in Python

List Comprehensions are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Let’s take a look at some examples to understand what nested list comprehensions can do:

Example 1:

I want to create a matrix which looks like below: matrix = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

The below code uses nested for loops for the given task:

matrix = []

for i in range[5]:

# Append an empty sublist inside the list

matrix.append[[]]

for j in range[5]:

matrix[i].append[j]

print[matrix]

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

The same output can be achieved using nested list comprehension in just one line:

# Nested list comprehension

matrix = [[j for j in range[5]] for i in range[5]]

print[matrix]

Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Explanation:

The syntax of the above program is shown below:

[expression for i in range[5]] –> which means that execute this expression and append its output to the list until variable i iterates from 0 to 4.

For example:- [i for i in range[5]] –> In this case, the output of the expression
is simply the variable i itself and hence we append its output to the list while i
iterates from 0 to 4.

Thus the output would be –> [0, 1, 2, 3, 4]

But in our case, the expression itself is a list comprehension. Hence we need to first
solve the expression and then append its output to the list.

expression = [j for j in range[5]] –> The output of this expression is same as the
example discussed above.

Hence expression = [0, 1, 2, 3, 4].

Now we just simply append this output until variable i iterates from 0 to 4 which would
be total 5 iterations. Hence the final output would just be a list of the output of the
above expression repeated 5 times.

Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Example 2:

Suppose I want to flatten a given 2-D list: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Expected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]

This can be done using nested for loops as follows:

# 2-D List

matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

flatten_matrix = []

for sublist in matrix:

for val in sublist:

flatten_matrix.append[val]

print[flatten_matrix]

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Again this can be done using nested list comprehension which has been shown below:

# 2-D List

matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# Nested List Comprehension to flatten a given 2-D matrix

flatten_matrix = [val for sublist in matrix for val in sublist]

print[flatten_matrix]

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

In this case, we need to loop over each element in the given 2-D list and append it
to another list. For better understanding, we can divide the list comprehension into
three parts:

flatten_matrix = [val for sublist in matrix for val in sublist]

The first line suggests what we want to append to the list. The second line is the
outer loop and the third line is the inner loop.

‘for sublist in matrix’ returns the sublists inside the matrix one by one which would be:

[1, 2, 3], [4, 5], [6, 7, 8, 9]

‘for val in sublist’ returns all the values inside the sublist.

Hence if sublist = [1, 2, 3], ‘for val in sublist’ –> gives 1, 2, 3 as output one by one.

For every such val, we get the output as val and we append it to the list.

Example 3:

Suppose I want to flatten a given 2-D list and only include those strings whose lengths are less than 6:

planets = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]]

Expected Output: flatten_planets = [‘Venus’, ‘Earth’, ‘Mars’, ‘Pluto’]

This can be done using an if condition inside a nested for loop which is shown below:

# 2-D List of planets

planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]

flatten_planets = []

for sublist in planets:

for planet in sublist:

if len[planet] < 6:

flatten_planets.append[planet]

print[flatten_planets]

Output: ['Venus', 'Earth', 'Mars', 'Pluto']

This can also be done using nested list comprehensions which has been shown below:

# 2-D List of planets

planets = [['Mercury', 'Venus', 'Earth'], ['Mars', 'Jupiter', 'Saturn'], ['Uranus', 'Neptune', 'Pluto']]

# Nested List comprehension with an if condition

flatten_planets = [planet for sublist in planets for planet in sublist if len[planet] < 6]

print[flatten_planets]

Output: ['Venus', 'Earth', 'Mars', 'Pluto']

Explanation:

This example is quite similar to the previous example but in this example, we just
need an extra if condition to check if the length of a particular planet is less than
6 or not.

This can be divided into 4 parts as follows:

flatten_planets = [planet for sublist in planets for planet in sublist if len[planet] < 6]


Article Tags :

Python

Technical Scripter

python-list

Technical Scripter 2018

Practice Tags :

python-list

Chủ Đề