Reputation: 169
I am self learning python and I was doing an exercise, the solution to which was posted in this thread. Could anyone translate into english what this piece of code means? When I learned if statements I never came across this syntax.
consonants = 'bcdfghjklmnpqrstvwxz'
return ''.join(l + 'o' + l if l in consonants else l for l in s)
Upvotes: 6
Views: 220
Reputation: 530990
This piece of code contains neither an if
statement nor a for
loop. You can tell most easily because statements cannot be embedded in an expression, such as the one being passed as the argument to join
.
consonants = 'bcdfghjklmnpqrstvwxz'
return ''.join(l + 'o' + l if l in consonants else l for l in s)
The if
is part of a conditional expression, which has the form x if y else z
. Unlike an if
statement, the else
is mandatory, because the expression must have a value whether or not y
is true. If y
is true, the value is x
; otherwise, the value is z
. In this case, the value is either l + 'o' + l
(when l
is a consonant) or l
itself.
The for
keyword is used to indicate a generator expression, which you can think of as essentially as a way to generate a sequence of values based on another sequence. Here, we start with the some sequence s
, and produce another value for each of the characters l
in that sequence. The resulting sequence is used by join
to produce a new string.
(Slightly off-topic, but it's more efficient to explicitly pass a list, not a generator, to join
, since it needs to build a list first anyway to figure out how much space to allocate for the resulting string.
return ''.join([l + 'o' + l if l in consonants else l for l in s])
)
Upvotes: 0
Reputation: 4130
It's a longer piece of code, written as a generator. Here is what it would look like, more drawn out.
consonants = 'bcdfghjklmnpqrstvwxz'
ls = []
for l in s:
if l in consonants:
ls.append(l + 'o' + l)
else:
ls.append(l)
return ''.join(ls)
It loops through s
and checks if l
is in the string consonants
. If it is, it pushes l + 'o' + l
to the list, and if not, it simply pushes l
.
The result is then joined into a string, using ''.join
, and returned.
More accurately (as a generator):
consonants = 'bcdfghjklmnpqrstvwxz'
def gencons(s):
for l in s:
if l in consonants:
yield l + 'o' + l
else:
yield l
return ''.join(gencons(s))
Where gencons
is just a arbitrary name I gave the generator function.
Upvotes: 11