1

I'm trying to generate unique permutations of length two from a string but I'm getting repeated values. What am I doing wrong? Here's the code:

a = 'abba'
from itertools import permutations
x = []
x = [y for y in list(permutations(a,2)) if y not in x]
'''
output was this:
[('a', 'b'), ('a', 'b'), ('a', 'a'), ('b', 'a'), ('b', 'b'), ('b', 'a'), ('b', 'a'), ('b', 'b'),('b', 'a'), ('a', 'a'), ('a', 'b'), ('a', 'b')]
'''

1 Answers1

1

The list comprehension builds a list, then assigns it to x, so x == [] the whole time it's running. Every time the list comprehension checks y not in x, x is still an empty list, so of course y is never in it.

If order isn't crucial, you could use a set instead:

x = set(permutations(a, 2))

Otherwise, unroll the list comprehension:

x = []
for y in permutations(a, 2):
    if y not in x:
        x.append(y)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437