# Excluding self-intersections when performing a linestring difference in shapely

I have a (complex) LineString (with 1 self-intersection):

``````ls_self_intersection = LineString([(1, 2), (4, 2), (4, 3), (3, 3), (3, 1)])
``````

and I have a (simple) LineString (with no self-intersection):

``````ls = LineString([(2, 1), (2, 3)])
``````

when I do a difference:

``````ls_diff = ls_self_intersection.difference(ls)
``````

the result is a MultiLineString

``````mls = mapping(ls_diff)
``````

with the following content

``````{
'type': 'MultiLineString',
'coordinates': (
((1.0, 2.0), (2.0, 2.0)),
((2.0, 2.0), (3.0, 2.0)),
((3.0, 2.0), (4.0, 2.0), (4.0, 3.0), (3.0, 3.0), (3.0, 2.0)),
((3.0, 2.0), (3.0, 1.0))
)
}
``````

I was expecting this result (excluding the self-intersection):

``````{
'type': 'MultiLineString',
'coordinates': (
((1.0, 2.0), (2.0, 2.0)),
((2.0, 2.0), (4.0, 2.0), (4.0, 3.0), (3.0, 3.0), (3.0, 1.0)))
)
}
``````

How can I exclude the self-intersection when performing the `difference` operation?

• Could you compare the set of points in a post-processing step and remove those that are superfluous? Commented Jan 16, 2021 at 12:20
• note: the result are linestrings. -> have not thought of this... :| you mean something like iterating over the original difference, concating the actual and the next linestring, performing difference on the concatenated linestrings with the other linestring (`ls`) to check if there is an intersection -> no: leave them concatenated and concatenate the next linestring, repeat difference... -> yes: concatenate next linestrings and perform a difference... do you intend something like this?
– udo
Commented Jan 16, 2021 at 15:31
• Yes, correct, that could work this way in my opinion Commented Jan 16, 2021 at 17:06