Luke
Luke

Reputation: 5708

Merging 2 lists in Python, giving one list precedence

I'm not looking to concatenate lists. I'm just wondering if there's a more Pythonic way to do this:

def merge(list1, list2):
  result = []
  result += list1
  if len(list2) > len(list1):
    result += list2[len(list1):]
  return result

so

a = [7,6,5,4,3,2,1]
b = [1,2,3,4,5,6,7,8,9,10] 
merge(a,b)
> [7,6,5,4,3,2,1,8,9,10] 

Note: I'm not sure if merge is the canonical term for what I'm trying to do here. Hopefully, it's clear what I'm asking though.

EDIT: I should have made it more clear, That code above does exactly what I want. I don't care about duplicates showing up. Basically,what I want is for all of the elements from the first list to be in the same positions in the resulting list, but I want the end of the resulting list to be padded with the elements corresponding to that index from the second list if the second list is bigger than the first list.

Here's another example:

a = [2,3,1,3,3,2]
b = [1,1,1,1,1,1,1,1,2,1,1]
merge(a,b)
 >  [2,3,1,3,3,2,1,1,2,1,1]
merge(b,a)
 >  [1,1,1,1,1,1,1,1,2,1,1]

Upvotes: 2

Views: 176

Answers (3)

Dunes
Dunes

Reputation: 40683

a + b[len(a):] should do what you want regardless of the lengths of either list. [1][1:] evaluates to an empty list. It's also guaranteed to make a new list that is independent of a and b.

Upvotes: 1

Babu
Babu

Reputation: 2598

You can use the list slicing if you don't care about the duplicates.

def merge(a, b):
    return a + b[len(a):]

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

You can add the first list with the filtered version of second list. You can use a list comprehension to loop over the items of b and keep the items that are not in a :

>>> a+[i for i in b if i not in a]
[7, 6, 5, 4, 3, 2, 1, 8, 9, 10]

Or you can use numpy:

>>> import numpy as np
>>> np.concatenate((a,np.setdiff1d(b,a)))
array([ 7,  6,  5,  4,  3,  2,  1,  8,  9, 10])

Upvotes: 2

Related Questions