How to replace only first instance of a value in a list which consists of multiple groups?

Question:

I have 2 lists and I want to change the elements of 2nd list based on groups of 1st list. Example I have:-

a=[1,1,1,2,2,2,2,3,3,3,4,4,4,5,5]
b=['','','l2','22','','','','','l3','l5','','l4','','','']

Both the lists have same number of elements. For every group of elements in ‘a list I only want to replace the value in list b at index 1 of each group present in list a.

Conditions : Only replace the value in list b if the element at that index(of list a) is empty or ” in list b.

If the first value in list b with respect to group of values in list a at index 1 is not empty dont change the further values i.e If the list b has already some value present at index 1 dont replace any value of that group with respect to indexes in list a.

For example: a=[1,1,1,1,2,2,2,2]=b[”,”,’l2,’l3′,’l4,”,”,”] then expected output is b=[‘value’,”,’l2′,’l3′,’l4′,”,”,”]

Expected Output:

['value', '', 'l2', 'l3', '', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']

Approach that I got suggested earlier by @Chris (which is correct)
but now I have a different requirement:

a=[1,1,1,2,2,2,2,3,3,3,4,4,4,5,5]
b=['','','l2','l3','','','','','l3','l5','','l4','','','']

from itertools import groupby
g = groupby(a)

i = 0
for group,data in g:
    n = len(list(data))
    b[b[i:i+n].index('')+i] = 'value'
    i+=n
    
    

print(b)

Output I’m getting:

['value', '', 'l2', 'l3', 'value', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']
Asked By: pratham bhatia

||

Answers:

IIUC, use a simple test:

a=[1,1,1,2,2,2,2,3,3,3,4,4,4,5,5]
b=['','','l2','l3','','','','','l3','l5','','l4','','','']

from itertools import groupby
g = groupby(a)

i = 0
for group, data in g:
    if not b[i]:
        b[i] = 'value'  # or b[i] = group if you want the value in a
    i += len(list(data))

output: ['value', '', 'l2', 'l3', '', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']

Answered By: mozway

One possible solution makes use of for-loops:

final_list = b.copy()

for idx in range(len(final_list)):
    if idx == 0 or a[idx] != a[idx-1]:
        if not final_list[idx]: final_list[idx] = 'value'

Another solution uses list comprehension:

final_list = ['value' if ((idx == 0 or a[idx] != a[idx-1]) and not b[idx]) else b[idx] for idx in range(len(b))]

Which creates the following output:
['value', '', 'l2', 'l3', '', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']

Answered By: MattFromGermany