0

Can anybody explain me whats wrong i am doing here -

multiArray = [
    ['one', 'two', 'three', 'four', 'five'],
    ['one', 'two', 'three', 'four', 'five'],
    ['one', 'two', 'three', 'four', 'five']
]
search ='four'
p1 = list(filter(lambda outerEle: search == outerEle, multiArray[0]))
p = list(filter(lambda multiArrayEle: list(filter(lambda innerArrayEle: search == innerArrayEle, multiArrayEle)), multiArray))
print (p1)
print (p)

The result i am getting here is

['four']
[['one', 'two', 'three', 'four', 'five'], ['one', 'two', 'three', 'four', 'five'], ['one', 'two', 'three', 'four', 'five']]

while i am expecting

[['four'],['four'],['four']]
1
  • 2
    You're trying to do far too much stuff in a single line. When you have a lambda in a lambda and your code doesn't work, that's a sign that you should split your code into more, shorter, readable lines. Commented Mar 16, 2019 at 18:21

2 Answers 2

4

In your second filter, you are using a list as a predicate (as opposed to simply a bool as you do in the first filter); now, this implicitly applies the built-in method bool to each element list, and for a list l, bool(l) is true exactly when l is non-empty:

In [4]: bool([])
Out[4]: False

In [5]: bool(['a'])
Out[5]: True

This allows you to pick out, for example, all the non-empty lists in a list of lists:

In [6]: ls = [['a'], [], ['b']]

In [7]: list(filter(lambda l: l, ls))
Out[7]: [['a'], ['b']]

Thus, in your case, at the end of the day, your filter ends up giving you all lists for which 'four' appears, which is all of them.

From your given example, it's not immediately obvious what you are trying to achieve as all the inputs are identical, but my guess is that it's something like the following:

In [19]: multiArray = [
    ...:     ['one', 'two', 'three', 'four', 'five', 'four'],
    ...:     ['one', 'two', 'three', 'for', 'five'],
    ...:     ['one', 'two', 'three', 'four', 'five']
    ...: ]

In [20]: [list(filter(lambda x: x == search, l)) for l in multiArray]
Out[20]: [['four', 'four'], [], ['four']]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quick reply. However what if i want to use lambda inside lambda. You might understood what i want to achieve. I want to search all lists inside a list for a particular word and want to get that searched list.
3

While @fuglede's answer is really the answer to your question, you can archive the result you want by changing your outer filter to map:

p = list(map(lambda multiArrayEle: list(filter(lambda innerArrayEle: search == innerArrayEle, multiArrayEle)), multiArray))

1 Comment

Thanks Bohdan. This is what i was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.