Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace elements in lists based on indexes python

Community of stackoverflow:

I have a list "rest" which is the following:

rest=[5, 7, 11, 4]

I have another list which is b:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b=[21, 22, 33, 31, 23, 15, 19, 13, 6]

And I have a "last" list:

last=[33, 19, 40, 21, 31, 22, 6, 15, 13, 23]

I have to replace the first 4 elements in b with the elements in rest. How can I replace the elements in last according to the matches with b to get the rest elements?

for example:

     5   7   11   4   #elements from rest
b= [21, 22, 33, 31, 23, 15, 19, 13, 6]

to get last list as the following:

last=[11, 19, 40, 5, 4, 7, 6, 15, 13, 23]  #elements that matched with b were replaced by rest

How can I do this?

>Solution :

Try this:

rest=[5, 7, 11, 4]
b=[21, 22, 33, 31, 23, 15, 19, 13, 6]
last=[33, 19, 40, 21, 31, 22, 6, 15, 13, 23]

for i, l in enumerate(last):
    if l in b:
        if b.index(l) < len(rest):
            last[i] = rest[b.index(l)]
            
print(last)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading