This piece of code contains neither an if nor a for loop. You can say it most easily, because statements cannot be embedded in an expression, such as the one that is passed as the join argument.
consonants = 'bcdfghjklmnpqrstvwxz' return ''.join(l + 'o' + l if l in consonants else l for l in s)
if is part of a conditional expression that has the form x if y else z . Unlike the if , the else parameter is required, because the expression must be true or not. If y true, the value of x ; otherwise, the value of z . In this case, the value is either l + 'o' + l (when l is consonant) or l .
The for keyword is used to denote a generator expression, which you can think of as essentially a way to generate a sequence of values ββbased on another sequence. Here we start with some sequence s and create a different value for each of the characters l in this sequence. The resulting sequence is used by join to create a new line.
(A bit off topic, but itβs more efficient to explicitly pass the list, rather than the generator, to join , since it needs to first create a list to determine how much space is allocated for the resulting row.
return ''.join([l + 'o' + l if l in consonants else l for l in s])
)
source share