Reputation: 5871
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)]
Upvotes: 3
Views: 433
Reputation: 17247
There is a new feature available only in Python 3.5:
Unpacking of iterables anywhere in a list:
[prefix, *iterable, suffix]
(I wish they added it sooner)
Upvotes: 2
Reputation: 3525
As an alternative if speed is critical, thought I'd offer this approach. You can use a deque
which has native support for appending to either the head or tail of the structure.
It's a double-ended queue data structure, and as such offers O(1) prepending as opposed to O(n) for lists.
from collections import deque
dq = deque(range(1,10)) # Test list passed to deque -> deque([1, 2, 3, 4, 5, 6, 7, 8, 9])
dq.appendleft(0)
dq.append(10)
print dq
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Upvotes: 1
Reputation: 1812
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]
Upvotes: 4