Vicrobot
Vicrobot

Reputation: 3988

Single statement containing if statement and for loop

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

Answers (2)

fferri
fferri

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

dimm
dimm

Reputation: 1798

That is a python list comprehension.

Upvotes: 1

Related Questions