Reputation: 4561
How I can loop over a python list, add each item to another list except the current item:
list = [1,2,8,20,11]
for i,j in enumerate(list):
print j[i+1:]
#this will only give [2,8,20,11] then [8,20,11],[20,11], [11]
#but I want something like [2,8,20,11], [1,8,20,11],[1,2,20,11]... etc.
#then 1,8,20,11
#then
Upvotes: 1
Views: 76
Reputation: 142136
Looks like you're after combinations
, eg:
>>> from itertools import combinations
>>> data = [1,2,8,20,11]
>>> list(combinations(data, 4))
[(1, 2, 8, 20), (1, 2, 8, 11), (1, 2, 20, 11), (1, 8, 20, 11), (2, 8, 20, 11)]
Upvotes: 3
Reputation: 22954
you may use list slicing as:
lst = [1,2,8,20,11]
for i in xrange(len(lst)):
print lst[:i]+lst[i+1:]
>>> [2, 8, 20, 11]
[1, 8, 20, 11]
[1, 2, 20, 11]
[1, 2, 8, 11]
[1, 2, 8, 20]
Upvotes: 2