0

I have a list of lists containing numbers as follows:

scc = [[6], [17, 7], [11, 10, 20, 1], [8, 18, 22, 13, 3], [4, 14, 23, 28, 9, 27, 19, 25, 24, 5, 15, 31, 30, 12, 26, 21, 2]]

and a used numbers list as follows:

used = [6,7,20,4]

and I want to remove those used numbers from scc list of lists and if any list boils down to one element and I want to remove that element from it I want to remove the whole list from scc.

scc = [[number for number in group if number not in used] for group in scc]

scc = [[], [17], [11, 10, 20, 1], [8, 18, 22, 13, 3], [14, 23, 28, 9, 27, 19, 25, 24, 5, 15, 31, 30, 12, 26, 21, 2]]

but I want to remove the list in scc if it's length is == 0 like the first list so that scc would be outputed as that:

scc = [[17], [11, 10, 20, 1], [8, 18, 22, 13, 3], [14, 23, 28, 9, 27, 19, 25, 24, 5, 15, 31, 30, 12, 26, 21, 2]]

Is there an elegant way to do it?

Mahmoud Ayman
  • 197
  • 1
  • 13
  • 2
    you cannot remove an item from a list while iterating through it – Julien Spronck May 01 '15 at 11:23
  • 2
    Don't remove items from a list you're iterating over – Tim May 01 '15 at 11:23
  • @JulienSpronck Then what should I do? – Mahmoud Ayman May 01 '15 at 11:25
  • 3
    @MahmoudAyman Create a new list, but filter out the values you don't want – Peter Wood May 01 '15 at 11:26
  • @PeterWood I saw the case of the duplicate question and its a list so he did that: `L[:] = [el for el in L if el != 3]` but in my case it's a list of lists so how can I do this? – Mahmoud Ayman May 01 '15 at 11:35
  • @PeterWood I used this `b = [[number for number in group if number not in used] for group in scc]` but is there an elegant way to delete list in the list with len == 0? – Mahmoud Ayman May 01 '15 at 12:00
  • 1
    @MahmoudAyman `b = [[number for number in group if number not in used] for group in scc if not set(used).issuperset(group)]` – Peter Wood May 01 '15 at 12:04
  • Thank you very much although I don't understand what does `set(used).issuperset(group)` do but that definitely helped me. – Mahmoud Ayman May 01 '15 at 12:07
  • @MahmoudAyman [set](https://docs.python.org/2/library/stdtypes.html#set) is a builtin type which stores unique items. You can compare a set with another sequence, just like you would in maths. So, it's saying we'll create the list if the group integers aren't completely contained by the set of used integers. – Peter Wood May 01 '15 at 12:10

0 Answers0