Please walk me through list comprehension syntax?

So this list comprehension section uses the following code:

usernames = [word for word in words if word[0] == '@']

Could someone walk me through what’s happening with the part [word for word in words if word[0] == ‘@’] ? I get the final part (if the first character is an @ symbol) but I really have no clue what the rest of the code is doing. Honestly, I really think it’s the starting “word for” that I’m not getting. The rest makes sense, it’s just visually difficult through repetition of the same word word.

Reminds me of Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.

There are four components in the above expression.

  • a list object (words)
  • a for loop (with word as iteration variable)
  • a conditional
  • a list of captured values
[word for word in words if word[0] == '@']
                  _____
                     \
                    list object

[word for word in words if word[0] == '@']
      _________________
              \
             for loop

[word for word in words if word[0] == '@']
                        _________________
                                 \
                              conditional

[word for word in words if word[0] == '@']
 ____
   \
  capture value
2 Likes

Thanks, this explained it well.

To be honest I actually figured it out in the very next lesson. I’m finding a pretty common pattern that when something isn’t fully fleshed out when I first encounter it, it’s explained better when the next chapter uses a different example.

Like Doctor Strange said: the warnings come after the instructions.

1 Like