0
L = [9, 2, 1, 3, 4, 5, 6]


x = str(filter(lambda x: x > 30, map(lambda x: x*x, L)))

I know that in order to remove the or whatever at the output, I can add a list() in front or tuple (). I know the answer for x is [81, 36], but how do I actually produce it at the output? I cant seem to make it work with list() or tuple()

3 Answers3

0

You are converting it to a str.. remove the str()

x = list(filter(lambda x: x > 30, map(lambda x: x*x, L)))
Sam Daniel
  • 1,800
  • 12
  • 22
0

Converting the filter-object to str will only covert it to str:

x = str(filter(lambda x: x > 30, map(lambda x: x*x, L)))
print(type(x)) # <class 'str'>

What you need is to convert it into list instead of str:

L = [9, 2, 1, 3, 4, 5, 6]
x = list(filter(lambda x: x > 30, map(lambda x: x*x, L)))

OUTPUT:

[81, 36]
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

filter() is an equivalent of defining a generator with the same behavior, not a list. Generators have the property of generating the values not until you call the generator's __next__() member function, what is essentially what happens during iteration.

As other answers stated, you can convert a generator to a list using list() (see here for example), but be aware that generators are one-time-use objects, and trying to use list() a second time will result in an empty list.

The python docs say

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

pguenther
  • 112
  • 8