angussidney
angussidney

Reputation: 686

How to write a Lambda with a for loop in it

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?

Upvotes: 2

Views: 21061

Answers (3)

BrianO
BrianO

Reputation: 1514

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]

Upvotes: 5

Clodion
Clodion

Reputation: 1017

Why not multiplying?

>>> lst = [None]*5
>>> lst
[None, None, None, None, None]
>>> lst[1] = 4
>>> lst
[None, 4, None, None, None]

Why not list comprehension?

>>> lst = [None for x in range(5)]
>>> lst
[None, None, None, None, None]
>>> lst[3] = 9
>>> lst
[None, None, None, 9, None]

But… With lambda:

>>> k=lambda x: [None]*x
>>> lst = k(5)
>>> lst
[None, None, None, None, None]
>>> lst[4]=8
>>> lst
[None, None, None, None, 8]

Upvotes: 3

Tom Karzes
Tom Karzes

Reputation: 24052

You don't need a lambda for this. All you need is:

[None] * len(string)

Upvotes: 1

Related Questions