Home > OS >  moving elements from list of list [closed]
moving elements from list of list [closed]

Time:10-01

I have a list of list, k=[[1,2,3],[2,5,6],[2],[1,7,8,3]]

If there is any list within list k which has single element like [2] here, I want to remove it from k, and append/move to some different list.

How can I do that?

Thanks!

CodePudding user response:

You can pop with idx form k then append to list that you want.

Try this:

>>> k = [[1,2,3],[2],[3],[1,7,8]]

>>> idx = 0
>>> out = []
>>> while idx < len(k):
...    if len(k[idx])==1:
...        out.append(k.pop(idx))
...        idx -= 1
...    idx  = 1
      
        
>>> k
[[1, 2, 3], [1, 7, 8]]


>>> out
[[2],[3]]
  • Related