1

For example if i have an list containing integers

arr = [1,2,3,4,5,6]

I would like to split this list into two lists based on specific indexes. If i specify the indexes 0,1 and 3 it should return the old list with the removed items and a new list containing only the specified items.

arr = [1,2,3,4,5,6]

foo(arr, "013"): # returns -> [3,5,6] and [1,2,4]

4 Answers4

2

Here's one way using a generator function, by popping the elements from the input list, while they are yielded from the function.

Given that the items in the list are being removed while iterating over it, it'll be necessary to sort in reverse order the list of indices, so that the indices of the actual values to remove in the input list remain unchanged while its values are being removed.

def foo(l, ix):
    for i in sorted(list(ix), reverse=True):
        yield l.pop(int(i))

By calling the function we get the values that have been removed:

arr = [1,2,3,4,5,6]

list(foo(arr, "013"))[::-1]
# [1, 2, 4]

And these have been removed from the original list:

print(arr)
# [3, 5, 6]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Hi you should look as pop() function.

Using this function is modifying the list directly.

The code should look like :

def foo( arr, indexes):
   res= []
   # process list in descending order to not modify order of indexes
   for i in sorted(indexes, reverse=True):
        res = arr.pop(i)
   return res, arr

Thus foo(arr, [0,1,3]) is returning : [3,5,6], [1,2,4]

Clem G.
  • 396
  • 3
  • 8
0

Created one solution based on How to remove multiple indexes from a list at the same time? which does not use yield.

arr = [1,2,3,4,5,6]
indexes = [0,1,3]

def foo(arr, indexes):
    temp = []
    for index in sorted(indexes, reverse=True):
        temp.append(arr.pop(index))
    return arr, temp # returns -> [3, 5, 6] and [4, 2, 1]
0

This is what you need:

def foo(arr,idxstr):
        out=[] # List which will contain elements according to string idxstr
        left=list(arr) # A copy of the main List, which will result to the exceptions of the list out
        for index in idxstr: # Iterates through every character in string idxstr
                out.append(arr[int(index)]) 
                left.remove(arr[int(index)])
        return(out,left)