Home > Back-end >  Merge two lists, replacing elements with same index in Python
Merge two lists, replacing elements with same index in Python

Time:05-18

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:

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?

CodePudding user response:

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

  • Related