# Getting the polygons contained in closed MultiLinestring using Python

Given a set of "streets", how can I get the "blocks" contained in those streets?

For example, I'd like to extract four blocks / polygons from this 2 x 2 "checkerboard":

``````l1 = LineString([(0,0), (0, 2)])
l2 = LineString([(0,1), (1, 1)])
l3 = LineString([(0,1), (2, 1)])
l4 = LineString([(2,0), (2, 2)])
l5 = LineString([(0,2), (2, 2)])
l6 = LineString([(1,0), (1, 2)])
l7 = LineString([(0,0), (2, 0)])

my_lines = [l1, l2, l3, l4, l5, l6, l7]
blocks = gp.GeoSeries(my_lines).unary_union
``````

Is there a single function by which I can do this (perhaps if I add a buffer to each LineString)?

Use first `shapely.ops.polygonize`, then use `difference` to get block polygons.

``````from shapely.geometry import LineString, MultiLineString
from shapely.ops import polygonize

l1 = LineString([(0,0), (0, 2)])
l2 = LineString([(0,1), (1, 1)])
l3 = LineString([(0,1), (2, 1)])
l4 = LineString([(2,0), (2, 2)])
l5 = LineString([(0,2), (2, 2)])
l6 = LineString([(1,0), (1, 2)])
l7 = LineString([(0,0), (2, 0)])

lines = [l1, l2, l3, l4, l5, l6, l7]

polygon = list(polygonize(lines))[0]

eps = 0.001
buffer = MultiLineString(lines).buffer(eps)

# Difference
diff = polygon.difference(buffer)

# export the multipolygon as polygons
block_polygons = [geom for geom in diff.geoms]

print(block_polygons)

# OUT
# [<shapely.geometry.polygon.Polygon,
#  <shapely.geometry.polygon.Polygon,
#  <shapely.geometry.polygon.Polygon,
#  <shapely.geometry.polygon.Polygon]
``````