nums_lst = [x for y in matrix for x in y]
Could anyone please help me understand what does the line x for y in matrix for x in y
mean? matrix is of type list[[]]
What is x
and what is y
in the matrix?
Thank you for your help.
nums_lst = [x for y in matrix for x in y]
Could anyone please help me understand what does the line x for y in matrix for x in y
mean? matrix is of type list[[]]
What is x
and what is y
in the matrix?
Thank you for your help.
This is called list comprehension. There’s plenty of tutorials but it’s basically flattening 3 or 4 lines of code into one. Put anyway instead of creating a list within a loop you use this special syntax. Here’s a good description of the technique enter link description here
You can also use dictionary comprehensions.
Once you get used to the syntax then comprehensions do result in nice clean code.
I suggest the following learning path. Try figure out a basic list comprehension first, for example take a list of integers and turn it into a list of squared integers. Then move onto the two dimensional element.