Exercise 41 - a for loop i don't understand

I’m going through the code in EX41, commenting it out and translating everything into my own noob programming language.

However I’ve hit a dead end on a for-loop. I tried googling it, but didn’t find anything. I hope someone in here can put it in black and white for me.

my problem is:

class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]

I understand what the code does, I just don’t understand what ‘w.capitalize()’ does before the ‘for’ in the for loop?
Can you put anything before a for-loop as long as it refers to the variable in the loop?
Can I put anything in front of a for-loop?

This is my full code.

def convert(snippet, phrase): #function called convert that takes snippet and phrase as parameters
    #class_names = a list with a for loop inside with w as a variable and takes random.sample(WORDS, snippet.count("%%%")) as a range

        #capitalize converts the the first charecter into CAP of w (the iterating variable).

        #random.sample(sequence,k) -> Sequcende can be a list, tuple, string or set. k and integer value that specify the length of a sample. `
        #fx if the sequecene has 5 words and k is 3 then the return will be 3 random words from the 5 words in the sequence `
            # in random is the sampe function that takes WORDS and snippet (the parameter from the parent function)
            # takes the snippet parameter and counts how many times "***" occours
        #random.sample(the list of words from WORDS, countes how many times "%%%" occours in the snippet)
        #returns and random sample of the list of WORDS, the amount depends on how many time '%%%' appears in snippet.
      
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]

Hi @ktrager

It’s me again. :yum:

The whole code is a ”class exercise machine”

It pick words from the file (words.txt) and create different parts of a class for the user to complete.

This very part make sure the name of the class begins with an upper case letter.

I hope this was answer to your question.

1 Like

That’s a special for-loop called a “list comprehension” https://en.wikipedia.org/wiki/List_comprehension which is basically inverting a forloop and dropping it inside a list to produce a new list. I’ll give an example that’s simpler than the above:

x = [1,2,3,4]
odds = []

for i in x:
    if i % 2 == 1:
        odds.append(i)

Keep in mind I didn’t run this code, but the gist is that it’s a for-loop that goes through x and if a number is odd (% 2 == 1 is how you test for odd, figure out why) then it adds it to the odd list. This kind of “filtering” is so common in programming that people figured out list comprehensions as a simplification:

>>> x = [1,2,3,4]
>>> odd = [i for i in x if i % 2 == 1]
>>> odd
[1, 3]

That’s a python shell where I do it, and you can start to map this for loop to the one above. Basically it’s kind of like I inverted the first for-loop like you’d invert a sock after taking it off your foot. If that makes sense.

  • odd = [ – I want a new list named odd
  • i for i – I want a new variable i that comes from the for-loop for i in...
  • in x – The new for-loop is inside x, just like for i in x above.
  • if i % 2 == 1 – This is the same as the if-statement above, but it’s acting like a filter.

Now you might ask, why do i for i? The for i part defines the loop, but what if I don’t want i but instead if want something on i? That first i for i let’s me call functions on it, so I could also do i.blah() for i in.

Try doing a few for-loops the normal way, then convert them to list comprehensions to get it.

1 Like

I’m happy you’re here to take all my question.
I feel I soon have to send you a huge box of cookies for all your help.

However I understand that w.capitalize makes sure all words in w starts with a CAP.
I was more questioning why it was put before the for loop. But think @zedshaw answered this below.

Thank you so much for this @zedshaw - I think this will stick with me for some time…:grin:

So basically this means that:

class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]

is the short version of:

class_names=[]

    for w in random.sample(WORDS, snippet.count("%%%")):
        class_names.append(w.capitalize())

I tried a few list comprehensions without the first ‘i’.
It seems ‘i’ has to be there whether i want to run a function on ‘i’ or not?

Yep, you’ve got it. They make you do “i for i” … oh well.

1 Like

Can someone elaborate more about what this code do and what is the meaning of these symbols %%%%. Any links that are helpful to learn more about how to use these symbols and other ones

Suppose snippet is another string that possibly contains a number of ‘%%%’ substrings. Then snippet.count('%%%') will count those substrings.

There is no special meaning to these symbols. Well… there is in other contexts, but here they’re just used as placeholders that get replaced by other strings.

1 Like