shuhalo
shuhalo

Reputation: 6462

Create copy of list and remove element

I would like to write something like this

S = [ 0, 1, 2 ]
F = [ S.without(i) for i in range(0,len(S)) ]
print F

and Python putting out

[ [0,1], [0,2] ,[1,2] ]

and have not found something like this in the online reference. Can you help me?

Upvotes: 2

Views: 6330

Answers (3)

senderle
senderle

Reputation: 151027

>>> S = [0, 1, 2]
>>> F = [S[0:i] + S[i+1:] for i in range(len(S))]
>>> print F
[[1, 2], [0, 2], [0, 1]]
>>> 

If you don't need the elements to be in any order -- that is, if you can use sets -- and if you want to remove items by value rather than by index, then this is a more elegant solution:

>>> S = set(range(3))
>>> F = [S - set((i,)) for i in S]
>>> F
[set([1, 2]), set([0, 2]), set([0, 1])]

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816600

Python provides itertools.combinations, which does exactly what you want:

>>> import itertools
>>> s = [0,1,2]
>>> list(itertools.combinations(s, len(s) - 1))
[(0, 1), (0, 2), (1, 2)]

Even better, it returns a generator, so you can easily iterate over all combinations without using much memory.

Upvotes: 6

bradley.ayers
bradley.ayers

Reputation: 38382

A nested list comprehension can do the job:

>>> S = [ 0, 1, 2 ]
>>> F = [[x for x in S if x != s] for s in S]
>>> print F
[[1, 2], [0, 2], [0, 1]]

Upvotes: 1

Related Questions