Morpheus
Morpheus

Reputation: 3523

How to concatenate lists in python but keeping only either the last or first element of adjacent lists if the elements are equal

This seems like an easy thing to achieve but googling has left me with nothing useful.

I have say four lists like this: [0,1,3], [3,5,6], [6,5,8], [9,1]

I want to concatenate them but after concatenating, I just want, for example the only one 3 from concatenating 1st and 2nd lists, only one 6 from concatenating 2nd and 3rd but concatenating the 3rd and 4th should not remove any elements.

The output should be

[0,1,3,5,6,5,8,9,1]

I can not obviously concatenate the lists using the + and remove the duplicates or as some other elements might get removed. I have thought about some logic but it is not very "pythonic". Any way to do this easily?

Upvotes: 1

Views: 69

Answers (2)

Alex Hall
Alex Hall

Reputation: 36013

from functools import reduce

lists = [[0, 1, 3], [3, 5, 6], [6, 5, 8], [9, 1]]


def add(a, b):
    if a and b and a[-1] == b[0]:
        a = a[:-1]
    return a + b


combined = reduce(add, lists)
assert combined == [0, 1, 3, 5, 6, 5, 8, 9, 1]

Upvotes: 3

exhuma
exhuma

Reputation: 21697

I don't think that there is a builtin method to help with this so you have to implement it yourself. Here's one way of doing it:

lists = [
    [0,1,3],
    [3,5,6],
    [6,5,8],
    [9,1]
]

output = []
for lst in lists:
    if not output:
        output.extend(lst)
        continue
    if output[-1] == lst[0]:
        output.extend(lst[1:])
        continue
    output.extend(lst)

print(output)

Upvotes: 1

Related Questions