1

I have inherited some Python scripts and I'm working to understand them. I am a beginner-level Python programmer but very experienced in several other scripting languages.

The following Python code snippet generates a file list which is then used in a later code block. I would like to understand exactly how it is doing it. I understand that os.path.isfile is a test for filetype and os.path.join combines the arguments in to a filepath string. Could someone help me understand the rest?

flist = [file for file in whls if os.path.isfile(os.path.join(whdir, i, file))]
3
  • 5
    docs.python.org/2/tutorial/… Commented Aug 6, 2014 at 22:27
  • 1
    things_we_want = [thing for thing in list_of_things if we_want(thing)] Commented Aug 6, 2014 at 22:29
  • @Davidmh that's possibly the most concise means of explanation I've ever seen.... Commented Aug 6, 2014 at 22:32

3 Answers 3

1

whls is an iterable of some kind.

For each element in whls, it checks if os.path.join(whdir, i, that_element) is a file. (os.path.join("C:","users","adsmith") on Windows is r"C:\users\adsmith")

If so, it includes it in that list.

As @jonsharpe posted in the comments, this is an example of a list comprehension which are well worth your time to master.

Sign up to request clarification or add additional context in comments.

Comments

0

The list comprehension means that python will iterate over each member of whls (this is maybe a tuple/list?), and for each item, it will test whether os.path.join(whdir, i, file) is a file (as opposed to a directory etc). It will return a list containing only the elements from whls that pass this condition check.

Comments

0

This list comprehension is equivalent to the following loop:

flist = []
for file in whls:
    if os.path.isfile(os.path.join(whdir, i, file)):
        flist.append(file)

The list comprehension is more compact. Performance-wise, they are similar, with the list comprehension being a little faster because it doesn't load the append() method.

1 Comment

Thank you for the alternate code. It made it much easier to understand. I will work on learning list comprehension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.