-2

Part of code that I do not understand, how it work?

data_folders = [os.path.join(root, d) for d in sorted(os.listdir(root))
if os.path.isdir(os.path.join(root, d))]

Here is the link for the code: https://github.com/rndbrtrnd/udacity-deep-learning/blob/master/1_notmnist.ipynb

Screenshot for the entire code: enter image description here

Question: "os.path.join(root, d)" joins the path and folder name (d) which is coming from the for loop, one at a time. But I do not understand what is the use of "if" condition which is doing the same thing? (I guess)

molbdnilo
  • 55,783
  • 3
  • 31
  • 71
Kasid Khan
  • 196
  • 1
  • 1
  • 13
  • 2
    It's just building a list of sorted directory names – mhawke Mar 14 '21 at 05:20
  • Please post all code as text. Screenshots of code are not acceptable on Stack Overflow. – Klaus D. Mar 14 '21 at 05:28
  • 1
    @the23Effect the term is "list comprehension" – juanpa.arrivillaga Mar 14 '21 at 05:30
  • 1
    @the23Effect It's a called a *list comprehension*, there's also a generator expression with `( )` around it. – Klaus D. Mar 14 '21 at 05:30
  • 1
    "But I do not understand what is the use of "if" condition which is doing the same thing? (I guess)" It's not. it checks if the path created by `os.path.join` is a directory. – juanpa.arrivillaga Mar 14 '21 at 05:30
  • @KlausD. My bad initially the code did not show the square brackets and I saw the whole code later and forgot to change generator to comprehension. – the23Effect Mar 14 '21 at 05:33
  • @KlausD. I wanted to highlight the part of the code that I did not understand and make it easy to observe, hence the image. I have also given the link to the entire code in the post. Thank you for helping out. – Kasid Khan Mar 14 '21 at 05:33

2 Answers2

1

I read it like this:

Join path and folder name which is coming from the for loop one at a time, if the joined path and folder name is a directory. If not, just skip the said path.

The purpose of the code is to build a list of sorted directories.

Nicholas D
  • 1,729
  • 1
  • 4
  • 16
1

This is a list comprehension syntax. The internal part is actually a generator but the square bracket makes it as a list comprehension.

It contains three parts, and last part is optional.

output_list = [
    generate something                  # Part 1: this will be the output content.
    from some iterable                  # Part 2: this is where you pick elements from.
    which matches a condition           # Part 3: this is the optional condition to match.
]

So for your question this is how it should be read,

data_folders = [
    os.path.join(root, d)                       # Part 1: generate this.
    for d in sorted(os.listdir(root))           # Part 2: from these.
    if os.path.isdir(os.path.join(root, d))     # Part 3: if they meet this condition.
]
the23Effect
  • 430
  • 2
  • 7