I am trying to make an empty list the same length as the number of letters in a string:
string = "string"
list = []
#insert lambda here that produces the following:
# ==> list = [None, None, None, None, None, None]
The lambda should do the equivalent of this code:
for i in range(len(string)):
list.append(None)
I have tried the following lambda:
lambda x: for i in range(len(string)): list.append(None)
However it keeps replying Syntax Error and highlights the word for.
What is wrong with my lambda?
You want a lambda that takes a string s and returns a list of length len(s) all of whose elements are None. You can't use a for loop within a lambda, as a for loop is a statement but the body of a lambda must be an expression. However, that expression can be a list comprehension, in which you can iterate. The following will do the trick:
to_nonelist = lambda s: [None for _ in s]
>>> to_nonelist('string')
[None, None, None, None, None, None]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With