filter fine, but you have to apply it outside the loop. The problem with your code is that you are passing the string to filter , so str ing is treated as iterative and repeated one character at a time. Since the character is a string of size 1, x[1] guaranteed beyond the bounds.
Try the following:
from itertools import permutations perms = list(filter(lambda x: x[1] != 'b', permutations(items))) # remove list(..) if you're using python2
If you need a list of lines, you can use map :
perms = list(map(''.join, filter(lambda x: x[1] != 'b', permutations(items))))
Or, as a list comprehension:
perms = [''.join(p) for p in permutations(items) if p[1] != 'b']
If you want to print it as you create it, use a loop instead:
for p in permutations(items): if p[1] != 'b': print(''.join(p))
In addition, the filter condition includes elements in which the condition is true, so your condition needs a little modification if you want to exclude lines whose first character is b (you will need x[1] != b , not x[1] == b )
source share