Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create copy of list and remove element

Tags:

python

list

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?

like image 605
shuhalo Avatar asked Dec 11 '25 09:12

shuhalo


2 Answers

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.

like image 155
Felix Kling Avatar answered Dec 12 '25 23:12

Felix Kling


>>> 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])]
like image 21
senderle Avatar answered Dec 12 '25 22:12

senderle



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!