Silviu Tofan Silviu Tofan - 4 months ago 8
Python Question

Insert element to list based on previous and next elements

I'm trying to add a new tuple to a list of tuples (sorted by first element in tuple), where the new tuple contains elements from both the previous and the next element in the list.

Example:

oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]


(4,10) was constructed from and added in between (3,10) and (4,7).

Construct (x,y) from (a,y) and (x,b)


I've tried using enumerate() to insert at the specific position, but that doesn't really let me access the next element.

Answer
oldList = [(3, 10), (4, 7), (5,5)]

def pair(lst):
    # create two iterators
    it1, it2 = iter(lst), iter(lst)
    # move second to the second tuple
    next(it2)
    for ele in it1:
        # yield original
        yield ele
        # yield first ele from next and first from current
        yield (next(it2)[0], ele[1])

Which will give you:

In [3]: oldList = [(3, 10), (4, 7), (5, 5)]

In [4]: list(pair(oldList))
Out[4]: [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]

Obviously we need to do some error handling to handle different possible situations.

Comments