Reputation: 3988
I was reading pathlib
module; and found this:
[x for x in p.iterdir() if x.is_dir()]
where p is Path
object, and above line lists all sub directories under that directory.
I want to know what that above complex statement is trying to say, how both for loop and if statement are combined together and how can i make such statements by myself.
I am also wondering why that is wrapped in []
.
Helps would be appreciated.
Upvotes: 1
Views: 412
Reputation: 18940
Writing:
lst = [x for x in p.iterdir() if x.is_dir()]
has the same effect of:
lst = []
for x in p.iterdir():
if x.is_dir():
lst.append(x)
and it is called a list comprehension.
Upvotes: 4