Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

nested loop in list comprehension

# 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)
Comment

python list comprehension nested loop

# This is the  syntax of a general list comprehension expression in Python
[expression 
 for x1 in it1 if cond1
 for x2 in it2 if cond2
 ...
 for xn in itn if condn
]

# hereby it1,..., itn are iterables and cond1, ..., condn boolean conditions
# expression can depend on x1,...,xn and
# itj and condj can depend on the variables x1,...,xj-1 quantified before it

# The list comprehension expression is equivalent to the following nested 
# for-loop statement
res = []
for x1 in it1:
	if cond1:
  		for x2 in it2: 
      		if cond2:
    			...
      			for xn in itn if condn:
                	if condn:
       					res.append(expression)
Comment

PREVIOUS NEXT
Code Example
Python :: Python - Sort Lists 
Python :: pandas convert string to numpy array 
Python :: python list insert vs append 
Python :: pd.loc 
Python :: what is not equals in python 
Python :: trim all new rows string python 
Python :: python arabic web scraping 
Python :: Python NumPy squeeze function Example 
Python :: change background create_text tkinter 
Python :: how to convert data into numerical dataset 
Python :: convert pdf to excel python 
Python :: how to make a window with tkinter 
Python :: 1d random walk in python stack exchange 
Python :: Print and remove previous line 
Python :: hide verbose in pip install 
Python :: reverse order of dataframe rows 
Python :: how to get all distinct substrings in a string python 
Python :: how i get url value in get_queryset function in drf 
Python :: godot remove node from group 
Python :: python ascii() 
Python :: no of words in a string in python 
Python :: PySimpleGUI multifiles select 
Python :: bst deleting in python 
Python :: create django model field based on another field 
Python :: how to format a file in python 
Python :: delete list using slicing 
Python :: pascal triangle 
Python :: enum python print all options 
Python :: Python Print Variable Using the f-string in the print statement 
Python :: jupyter dataframe print all 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =