-1

I found this post: How to list all files of a directory?

specifically:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

I'm still learning python, and I've used this line in a code for something at work, and I'd like to understand, specifically the "f for f". why is the same variable called twice? Thanks!

Community
  • 1
  • 1
Tak
  • 23
  • 4

2 Answers2

0

It could easily say x for x. It just means make a list of the f values for each f value in the directory listing if it is a file.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

It's not "called twice". It's just how you write a list comprehension. We can "unroll" this list comprehension into a for loop to make it easier to understand:

lst = []
for f in listdir(mypath):
    if isfile(join(mypath, f)):
        lst.append(f)

Explanation:

[f for f in listdir(mypath) if isfile(join(mypath, f))]
 ^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^
 |  |                       Condition to satisfy
 |  What to iterate over
 What to append to output list

The general rule of a list comprehension if that you are iterating over a source list (or some iterable), somehow modifying each element in that source or ensuring it satisfies some condition before appending it to your new output list.

Another example where you want to remove all non-positive numbers from a source list, and double all the positives:

src = [-1, -2, 0, 1, 2]
out = [i*2 for i in src if i > 0]
print(out)  # [2, 4]
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Thanks a lot everyone! As I mentioned, still very early at my learning stage. I will delete this post as I see this question was answered before, I just didn't know how to search it. Again, thank you very much all for your help. – Tak Dec 30 '15 at 07:03