Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)] 
like image 437
Kenny Ostrom Avatar asked Jan 20 '26 10:01

Kenny Ostrom


1 Answers

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]
like image 73
J Earls Avatar answered Jan 21 '26 23:01

J Earls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!