Nested loop for list in Python

List Comprehensions can use nested for loops. You can code any number of nested for loops within a list comprehension, and each for loop may have an optional associated if test. When doing so, the order of the for constructs is the same order as when writing a series of nested for statements. The general structure of list comprehensions looks like this:

[ expression for target1 in iterable1 [if condition1] for target2 in iterable2 [if condition2]... for targetN in iterableN [if conditionN] ]

For example, the following code flattening a list of lists using multiple for statements:

data = [[1, 2], [3, 4], [5, 6]] output = [] for each_list in data: for element in each_list: output.append[element] print[output] # Out: [1, 2, 3, 4, 5, 6]

can be equivalently written as a list comprehension with multiple for constructs:

data = [[1, 2], [3, 4], [5, 6]] output = [element for each_list in data for element in each_list] print[output] # Out: [1, 2, 3, 4, 5, 6]

Live Demo

In both the expanded form and the list comprehension, the outer loop [first for statement] comes first.

In addition to being more compact, the nested comprehension is also significantly faster.

In [1]: data = [[1,2],[3,4],[5,6]] In [2]: def f[]: ...: output=[] ...: for each_list in data: ...: for element in each_list: ...: output.append[element] ...: return output In [3]: timeit f[] 1000000 loops, best of 3: 1.37 µs per loop In [4]: timeit [inner for outer in data for inner in outer] 1000000 loops, best of 3: 632 ns per loop

The overhead for the function call above is about 140ns.

Inline ifs are nested similarly, and may occur in any position after the first for:

data = [[1], [2, 3], [4, 5]] output = [element for each_list in data if len[each_list] == 2 for element in each_list if element != 5] print[output] # Out: [2, 3, 4]

Live Demo

For the sake of readability, however, you should consider using traditional for-loops. This is especially true when nesting is more than 2 levels deep, and/or the logic of the comprehension is too complex. multiple nested loop list comprehension could be error prone or it gives unexpected result.


PDF - Download Python Language for free

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]fruits = ["apple", "banana", "cherry"] for x in adj:  for y in fruits:

    print[x, y]

Try it Yourself »


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.

You can use them to arrange data into hierarchical structures.

Create a Nested List

A nested list is created by placing a comma-separated sequence of sublists.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access Nested List Items by Index

You can access individual items in a nested list using multiple indexes.

The indexes for the items in a nested list are illustrated as below:

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h'] print[L[2]] # Prints ['cc', 'dd', ['eee', 'fff']] print[L[2][2]] # Prints ['eee', 'fff'] print[L[2][2][0]] # Prints eee

You can access a nested list by negative indexing as well.

Negative indexes count backward from the end of the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.

The negative indexes for the items in a nested list are illustrated as below:

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h'] print[L[-3]] # Prints ['cc', 'dd', ['eee', 'fff']] print[L[-3][-1]] # Prints ['eee', 'fff'] print[L[-3][-1][-2]] # Prints eee

You can change the value of a specific item in a nested list by referring to its index number.

L = ['a', ['bb', 'cc'], 'd'] L[1][1] = 0 print[L] # Prints ['a', ['bb', 0], 'd']

Add items to a Nested list

To add new values to the end of the nested list, use append[] method.

L = ['a', ['bb', 'cc'], 'd'] L[1].append['xx'] print[L] # Prints ['a', ['bb', 'cc', 'xx'], 'd']

When you want to insert an item at a specific position in a nested list, use insert[] method.

L = ['a', ['bb', 'cc'], 'd'] L[1].insert[0,'xx'] print[L] # Prints ['a', ['xx', 'bb', 'cc'], 'd']

You can merge one list into another by using extend[] method.

L = ['a', ['bb', 'cc'], 'd'] L[1].extend[[1,2,3]] print[L] # Prints ['a', ['bb', 'cc', 1, 2, 3], 'd']

If you know the index of the item you want, you can use pop[] method. It modifies the list and returns the removed item.

L = ['a', ['bb', 'cc', 'dd'], 'e'] x = L[1].pop[1] print[L] # Prints ['a', ['bb', 'dd'], 'e'] # removed item print[x] # Prints cc

If you don’t need the removed value, use the del statement.

L = ['a', ['bb', 'cc', 'dd'], 'e'] del L[1][1] print[L] # Prints ['a', ['bb', 'dd'], 'e']

If you’re not sure where the item is in the list, use remove[] method to delete it by value.

L = ['a', ['bb', 'cc', 'dd'], 'e'] L[1].remove['cc'] print[L] # Prints ['a', ['bb', 'dd'], 'e']

Find Nested List Length

You can use the built-in len[] function to find how many items a nested sublist has.

L = ['a', ['bb', 'cc'], 'd'] print[len[L]] # Prints 3 print[len[L[1]]] # Prints 2

Iterate through a Nested List

To iterate over the items of a nested list, use simple for loop.

L = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] for list in L: for number in list: print[number, end=' '] # Prints 1 2 3 4 5 6 7 8 9

Video liên quan

Chủ Đề