Shubham Malas
Shubham Malas

Reputation: 61

How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python

a = [9,8,2,3,8,3,5]

How to remove 2nd occurrence of 8 without removing 1st occurrence of 8 using remove()?

Upvotes: 6

Views: 9840

Answers (5)

Gouranga Satapathy
Gouranga Satapathy

Reputation: 432

python code to remove 2nd occurrence:

ls = [1, 2, 3, 2]
index = ls.index(2, 0)
lss = ls[index + 1:]
lss.remove(2)
print(ls[:index + 1]+lss)

Upvotes: 1

Vyachez
Vyachez

Reputation: 1001

This one if you need to delete second and following occurrence of a target item:

# deleting second and following occurrence of target item
a = [9,8,2,3,8,3,5]
b = []
target = 8 # target item
for i in a:
    if i not in b or i != target:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 3, 3, 5]

If you need to delete second and following occurrence for any item:

# deleting any second and following occurence of each item
a = [9,8,2,3,8,3,5]
b = []
for i in a:
    if i not in b:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 3, 5]

Now, when you need to delete only second occurrence of target item:

# deleting specific occurence of target item only (use parameters below)
a = [9,8,2,3,8,3,5,8,8,8]
b = []

# set parameters
target = 8 # target item
occurence = 2 # occurence order number to delete

for i in a:
    if i == target and occurence-1 == 0:
        occurence = occurence-1
        continue
    elif i == target and occurence-1 != 0:
        occurence = occurence-1
        b.append(i)
    else:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 8, 3, 5, 8, 8, 8]

Upvotes: 0

Akshit
Akshit

Reputation: 434

remove() removes the first item from the list which matches the specified value. To remove the second occurrence, you can use del instead of remove.The code should be simple to understand, I have used count to keep track of the number of occurrences of item and when count becomes 2, the element is deleted.

a = [9,8,2,3,8,3,5]
item  = 8
count = 0
for i in range(0,len(a)-1):
        if(item == a[i]):
               count =  count + 1
               if(count == 2):
                      del a[i]
                      break
print(a)

Upvotes: 1

cdlane
cdlane

Reputation: 41872

It's not clear to me why this specific task requires a loop:

array = [9, 8, 2, 3, 8, 3, 5]

def remove_2nd_occurance(array, value):

    ''' Raises ValueError if either of the two values aren't present '''

    array.pop(array.index(value, array.index(value) + 1))


remove_2nd_occurance(array, 8)

print(array)

Upvotes: 5

Austin
Austin

Reputation: 26039

Here's a way you can do this using itertools.count along with a generator:

from itertools import count

def get_nth_index(lst, item, n):
    c = count(1)
    return next((i for i, x in enumerate(lst) if x == item and next(c) == n), None)

a = [9,8,2,3,8,3,5]  
indx = get_nth_index(a, 8, 2)
if indx is not None:
    del a[indx]

print(a)
# [9, 8, 2, 3, 3, 5]

Upvotes: 2

Related Questions