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

Merge two lists, replacing elements with same index in Python

I would like to replace elements in one list with elements in another, but only as far as the second list goes.

For example:

defaults = ['apple','banana','cherry','date']
data = ['accordion','banjo']

#   result: ['accordion','banjo','cherry','date']

I can do it with a for loop, and I can do it in one line with the following code:

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

result = [data[i] if i<len(data) else defaults[i] for i,v in enumerate(defaults)]

Is there a simpler or more direct approach to doing this?

>Solution :

You want:

result = data + defaults[len(data):]

If data can be longer than defaults and you want the length of defaults to be the maximum length:

result = data[:len(defaults)] + defaults[len(data):]

This use of : is called ‘slicing’, more on slicing lists here python.org on Lists

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