How to partition a list of tuples around an element in Python?

Viewed 25

I have a list of sorted tuples that are (x, y) coordinates in a plane and I want to partition the points around a middle element. The points are sorted with respect to the point's x-coordinates.

P = [(-4.6, 1), (-2.5, -3), (-1.3, 5), (6, -2)]

I want to split P into two roughly equally sized lists of points using their x-coordinates. I'm not sure how to implement that. Here's what I tried

def partition(P):

    n = len(P)
    middle  = P[n // 2][0]

But middle returns a tuple, and I'm not sure how to partition P around middle's x-coordinate. Any help would be appreciated.

1 Answers

You almost have it. Just needed to use slicing to get a sublist rather than indexing which returns an element.

def partition(P):
    mid = len(P) // 2
    return P[:mid], P[mid:]
Related