Search code examples
pythonpython-3.xlambdapython-itertools

Itertools permutation with lambda


items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
    p1=(''.join(p))
    p2=filter(lambda x: x[1]=='b',p1)

I want to exclude strings with b on the second index. When I try to print the filter object

<filter at 0x7f8d729ba908>
for p in p2:
    print (p)

IndexError                                Traceback (most recent call last)
<ipython-input-27-fbcaa516953f> in <module>()
----> 1 for p in p2:
      2     print (p)

<ipython-input-23-c6289753f791> in <lambda>(x)
      1 for p in permutations(items):
      2     p1=(''.join(p))
----> 3     p2=filter(lambda x: x[1]=='b',p1)

IndexError: string index out of range

Is lambda right choice for this?Why do I have string index problem?


Solution

  • Each p is one permutation. So p2 is one string. If you filter it, your lambda function is being applied to each character in the string. So x[1] is out of range.

    Perhaps you mean something like this:

    strings = [''.join(p) for p in permutations(items)]
    strings = filter(lambda x: x[1]!='b', strings)
    

    or more simply

    strings = [''.join(p) for p in permutations(items) if p[1]!='b']
    

    (Using the condition p[1]!='b' to only include permutations where the second character is not 'b')