Can you break down the uses of the temporary variable `word` in the example?

Hello there,
Can someone help me to walk through the logic behind the syntax for list comprehension using the example before exercise? I have hard time understanding why we need to enter temporary variable word in front of the for loop?

words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = [**word** for word in words if word[0] == '@']

Per example, it says that this list comprehension:

  1. Takes an element in words -> I I understand that this happens via the for loop:
    for word in words
  2. Assigns that element to a variable called word -> I understand that this happens with every for loop when it assigns the value of the element it has found in the list to a temporary variable that we call here word

This is where I get stuck as I do not understand why we have to write word again in code before the for loop? What program “sees” when it hits this and why it can not run the code without it?
Thank you for the logic behind it!

3 Likes

lets look at the example:

words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = []

for word in words:
  if word[0] == '@':
    usernames.append(word)

the word variable in your question about list comprehension is equivalent to .append(word)

so its what we are appending to the list, this can be quite handy, for example:

result = [x ** 2 for x in range(1, 11) if x% 2 == 0 ]

this will give us the exponents of all even numbers from 1 till 11.

so we can manipulate what we append to the list, quite useful. Hope this helps

12 Likes

Thank you for your prompt attention and excellent example - I get it now!

At first glance it may be confusing, specially using that example

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

It reminded me of that old yo dawg meme (reference)

This is the way I made myself to understand this:

result_list = [expression for iteration_variable in iterable_list if condition]

Here

  • result_list is the list to be obtained after comprehension of iterable_list
  • expression is an expression which result will be appended to result_list, provided condition is True
  • iteration_variable is a dummy variable which takes the value of each element of iterable_list one at a time, does not need to be previously defined and only is used in the evaluation of expression and condition
  • condition is a logical expression applied to the current element of iterable_list (that is, to iteration_variable). If the result of condition is True, the result of expression is appended to result_list, if the result of condition is False, nothing happens with the current element of iterable_list and skips to the next element

Hope this helps to get a better insight of fellow python apprentinces.

3 Likes