How to write a Lambda with a for loop in it

12,916

Solution 1

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]

Solution 2

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]

Solution 3

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

[None] * len(string)
Share:
12,916

Related videos on Youtube

angussidney
Author by

angussidney

Hobbyist developer, gamer, and RPG player. Currently learning Node.js and Rails. I'm part of Charcoal, the organisation which keeps all the sites on SE free of spam and rude/abusive posts. Jump into our chatroom, Charcoal HQ, and get involved! You can contact me by emailing the following address (where you replace potato with my username): potato17 (at) gmail (dot) com Profile pictures by Lorc and Delapouite. Available on game-icons.net.

Updated on September 14, 2022

Comments

  • angussidney
    angussidney over 1 year

    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?

    • Sean Vieira
      Sean Vieira about 8 years
      lambdas can only contain expressions and for is a statement.