Kenny Ostrom Kenny Ostrom - 1 year ago 101
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]
return result

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

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download