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 :: webscrapping with python 
Python :: stack queue in python 
Python :: how to run terminal commands in python 
Python :: pyspark now 
Python :: how to count how many cameras you have with python 
Python :: python write text file on the next line 
Python :: python sort array by value 
Python :: how to change index date format pandas 
Python :: measure time 
Python :: how to bulk update in mongodb using python 
Python :: python using numpy 
Python :: convert np shape (a,) to (a,1) 
Python :: fibonacci series list comphrehension in python 
Python :: python - find specific name in a df 
Python :: check regex in python 
Python :: (for in) printing in python 
Python :: python initialize dict with empty list values 
Python :: picasa 
Python :: pandas dataframe compare two dataframes and extract difference 
Python :: d-tale colab 
Python :: getters and setters in python 
Python :: openpyxl check if worksheet exists 
Python :: asyncio run 
Python :: Write a Python program to sum all the items in a dictionary. 
Python :: python 7zip extract 
Python :: print python float precision 
Python :: create python list 
Python :: gspread_pandas pypi 
Python :: break all loops 
Python :: compare dates python 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =