2

can anyone explain in detail what this means? f for f in... for example

list = [f for f in os.listdir(os.getcwd()) if os.path.isdir(f)]
print(list)

I understand the syntax of basic for loops, but I've seen this type of thing numerous times and I find it pretty confusing. I've been searching and all I can find is info on formatting. I just started in python around a month ago and am still learning. Thank you for any help!

jstraugh
  • 110
  • 2
  • 7
  • 2
    Does this answer your question? [What does a for loop within a list do in Python?](https://stackoverflow.com/questions/11479392/what-does-a-for-loop-within-a-list-do-in-python) – marsnebulasoup Jul 02 '20 at 00:06
  • Beside the point, but [don't use `list` as a variable name since it shadows the builtin `list`](https://stackoverflow.com/q/77552/4518341). You could use `L` instead, for example. – wjandrea Jul 02 '20 at 02:08

3 Answers3

5

Let's say you want to create a list with values 0 to 100

list = [i for i in range(100)]

Here i will be added to the list while iterating from 0 to 100.

If you want any rule, you can use an if statement in the loop like:

list = [i for i in range(100) if i%2 == 0]

Here only numbers divisible by 2 will be added to the list because of the if statement.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
ByteWaiser
  • 136
  • 5
  • 1
    FWIW, the easier way to do the non-filtered one is `list(range(100))`. Though `range` already supports most operations `list` does, so casting it might be redundant, but I digress. – wjandrea Jul 02 '20 at 02:13
  • I know that but I did not have anything to iterate over this is the reason I used but thanks a lot. – ByteWaiser Jul 02 '20 at 15:41
3

It is called list comprehension.

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
ThunderPhoenix
  • 1,649
  • 4
  • 20
  • 47
3

This is a list comprehension. This loop would normally be written like this:

files = []
for f in os.listdir(os.getcwd()):
    if os.path.isdir(f):
        files.append(f)
marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37