Calin Paraipan
Calin Paraipan

Reputation: 31

Is it not possible to pass in a list to a lambda expression?

I am trying to print the squared values in a passed in list using a lambda expession.

squared = lambda x: x ** 2 
print(squared([1, 2, 3]))

This is the error that I am getting.

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

Upvotes: 0

Views: 4470

Answers (3)

Youyoun
Youyoun

Reputation: 338

lambda x: doSomethingWith(x) means that your function takes x as argument, and applies instructions to that argument. An "equivalent" code would be:

def f(x):
    return doSomethingWith(x)

The way you define squared means that your function takes as input a number and returns its square value. Which means you can't provide a list because your function definition takes a number as argument. There are multiple way you could use that on a list.

As others have mentionned, you could use map or list comprehension to "apply" your function on a list. That would mean that you're applying it to each element of the list (which is a number).

In case you want to use squared([1,2,3]), all you have to do is define a lambda function that takes a list as input and returns the squared of each number in that list. For instance you could use: squared = lambda x: [i**2 for i in x].

This is all to say that lambda can take a list as argument, but it all depends on how you want to use it.

Upvotes: 1

Sreekiran A R
Sreekiran A R

Reputation: 3421

You need to apply the function to all elements in list.

squared = lambda x: x ** 2 
print(list(map(squared,[1, 2, 3])))   

One faster approach would be using numpy

import numpy as np
print(np.array([1, 2, 3])**2)

EDIT: another approach using list comprehensions

def squared(list):
    return [i ** 2 for i in list]
print(squared([1,2,3]))

EDIT 2: Here, I think you got confused between lambda and def because you have defined the functions differently.

Your current def function.

def square (list1):
    list2 = [] 
    for num in list1:
        list2.append(num ** 2) 
    return list2 
print(square([1, 2, 3, 4]))

The equivalent of this in lambda would be

squared=lambda x:[y**2 for y in x]
print(squared([1,2,3,4]))

Upvotes: 2

Hemitheconyx
Hemitheconyx

Reputation: 44

You must map the lambda on the list, the pow (**) function expects a numeric type.

map takes a function and an iterable and returns a map object (which enables lazy computation), so if you want to get a list you can do

squared = lambda x: x ** 2
your_list = [1, 2, 3]
mapped_list = list(map(squared, your_list))
print(mapped_list) 

Upvotes: 0

Related Questions