-3

I have a list like this,

l=[1,2,3,4]

Now I want to create other lists from l where next value will be disappeared every time, so the output will be

[[2,3,4], [1,3,4],[1,2,4], [1,2,3]]

Few more examples,

 [1,2] --> [[2], [1]] 
 [10,32,15] --->[[32,15], [10,15], [10,32]]

I could do it using a for loop but am looking for a pythonic way to do it more efficiently.

Kallol
  • 2,089
  • 3
  • 18
  • 33

2 Answers2

0

You can use itertools.combinations for the job

list(itertools.combinations([1,2,3,4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

If you need the elements to be lists instead of tuples, a slight modification will do:

[list(elem) for elem in itertools.combinations([1,2,3,4], 3)]
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
Lukas Thaler
  • 2,672
  • 5
  • 15
  • 31
0
> old_list = [1, 2, 3, 4] 
> new_list = [] 
> for ITEM in old_list:
>     copy_old_list = old_list[:]
>     copy_old_list.remove(ITEM)
>     new_list.append(copy_old_list) 
> print(new_list)
[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]

In summary, add the entire list minus the item to a new list