Search code examples
pythonlistindexing

Remove items at given positions from a list


I am having difficulty finding a solution to my problem. I need to remove [4,1] from [4,4,4,1,1] and [5,2] from [5,5,2,2,1], only at their first occurrence. The desired result should be [4,4,1] and [5,2,1]. I appreciate your help. Thank you.


Solution

  • I made a function which is much simpler. This is similar to competitive programming. So from your question, it looks like, the default is the first number, then when a new number comes, it removes it and the previous number before it. code:

    #arr is array
    def convert(arr):
        default =arr[0]
        for i in range(len(arr)):
            if arr[i] != default:
                arr.pop(i)
                arr.pop(i-1)
                break
        print(arr)
    #put your list inside the function
    #convert()
    #example
    convert([4,4,4,1,1])
    convert([5,5,5,2,2])