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

60 Likes

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

1 Like

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.

59 Likes

Really nice explanation. Thanks :smiley:

I think a good and easy exemple should be this:
usernames = [word for word in words if word[0] == ‘@’]
Anyway the above example is confusing…
first you take a temp variable let say “X” and in order the program to understand what you are saying you need to say "hey, when I say X for now on is X " and then you need to say the “in X if X[0] == ‘@’”…
I am beginner as well, but this I see the things

this was so helpful in understanding the contetn better.

1 Like

best explanation i’ve seen. thanks for sharing.

1 Like

Even with this example I don’t understand. Could you help me to understand it in a more simple way?

I’m really having a difficult time understanding this.

What do you not understand?

list comprehension allows us to construct a list.

you can always consult external documentation if you need more information on something.

Great example.
To complement it:
The list comprehension example provided here:

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

Is strictly equivalent to the full code below:

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

By the way, the result of the code is the square of all even numbers from 1 till 10 (and not 11).

[4, 16, 36, 64, 100]

Hope it helps

2 Likes

i thought (un)till was exclusive:

https://ell.stackexchange.com/questions/33340/is-until-inclusive-or-exclusive

which seems to be the case unless there is a presence.

I am sure you are right as I am not an English native speaker.
The results of the code is the square of all even numbers from 1 inclusive to 10 inclusive.
Please advise if I should correct my original post.

that makes two of us, English isn’t my native language either.

yea, you are absolutely right. But given i though till was exclusive, till 11 (exclusive) is till 10 (inclusive). So we where saying the same thing

This was super helpful. Thank you!

1 Like

i want to print this out and hang it above my bed. Someone highlight this!

1 Like

This example uses “word” too much so I can see where it would confuse. Maybe I can help since I’m a beginner too. I think the code was something like:
username = [word for word in words if word[0] == “@”]
username = [word… This part is setting up a new variable, username, which will be a list built from iterations of another variable, word which is yet to be defined.
… for word in words… This is the way we typically use for. It defines a new variable word as each iteration of the elements of the list words. It sets up a loop where we will test each of those iterations or elements against some condition.
… if word[0] == “@” So this is the condition that must be met. The first character (we are indexing a string) of the word in words must be “@”. Now the condition is met and we will add the word to the list, username
Working middle out, this list comprehension makes more sense. for word in words we will test to see if word[0] == 0, and if it does, we build a list with the typical variable defining method, username = [word…

1 Like

I was really struggling with this example until i found this

newlist = [ expression for item in iterable if condition == True]

it seems like having the expression and item portion the same, is kind of like saying to x 1 before adding to the list, which we could change to something else if so desired (like the x ** 2 in @stetim94’s response)

the expression can be anything. And doesn’t even have to use the item, We can have:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_list = ["even number found" for item in  my_list if item % 2 == 0]

expression is what we normally .append() to a list.

1 Like