Kenny Ostrom Kenny Ostrom - 2 months ago 8
Python Question

Can list comprehension have a prefix, suffix?

I need to create a list comprehension and add one extra item at the start and end. Is there a better way than just using a helper function to do it?

# convert tuple from permutation into a list with predecessor and successor
def perm_to_list(predecessor, perm, successor):
result = [predecessor]
result.extend(list(perm))
result.append(successor)
return result

candidates = [perm_to_list(prefix, x, suffix)
for x in permutations(something)]

Answer

To match the sample code (where you add prefix and suffix to each element of a list comprehension)

candidates = [[prefix] + list(x) + [suffix] for x in permutations(something)]

To answer the question you actually asked (to add a prefix and suffix to the list comprehension itself)

candidates = [prefix] + [somefunction(x) for x in permutations(something)] + [suffix]