I have a list of the form L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
and I want to remove the third index where 1 occurs and replace it with 0. My code is this, but this removes the previous indexes of 1(1st and 2nd also) which I want in my List. My code is this
counter=0
index = 2
L = list([1, 2, 3, 4, 1, 2, 1, 3, 0, 4])
print("Value before is\n", L)
for i in range(len(L)):
y=L.index(1)
print(y)
if(counter==index):
L[y]=0
break
else:
counter=counter+1
L[y]
print("Value of list in else\n",L)
print("Value of counter\n",counter)
print("After the value is\n",L)
So output comes as
[2, 3, 4, 2, 0, 3, 0, 4]
but I want it as
L = [1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
and remember that I will not be given directly the index which I want to change
So I could Do L[7]=0
Thanks in advance
There are a few issues with your algorithm, but it boils down to this: by doing y = L.index(1)
you find the first index where a 1
appears. So by doing L[y] = 0
, all you can do is update the first occurence of a 1
.
There is no builin to find the nth appearance and so you will have to write it.
To be consistent with list.index
, I made the following index
function raise a ValueError
when the item is not found.
def index(lst, obj, n=1):
count = 0
for index, item in enumerate(lst):
if item == obj:
count += 1
if count == n:
return index
raise ValueError('{} is not in list at least {} times'.format(obj, n))
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
index = index(L, 1, n=3)
L[index] = 0
print(L)
[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
Alternatively, if all you want to do is replace the nth occurence, but do not care about its actual index, you can generate a new list with a list-comprehension and an itertools.count
object.
from itertools import count
def replace(lst, obj, repl, n=1):
counter = count(1)
return [repl if x == obj and next(counter) == n else x for x in lst]
L = [1, 2, 3, 4, 1, 2, 1, 3, 0, 4]
new_list = replace(L, 1, 0, n=3)
print(new_list)
[1, 2, 3, 4, 1, 2, 0, 3, 0, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With