Converting a python list to an SVG path


March 5, 2012

Here's a short snippet of Python code that was I very pleased with. It converts a list of coordinates, such as this:

[(10, 200), (12, 220), (15, 180)]

Into the d attribute of an SVG path, such as this:

"M10 200 L12 220 L15 180"

I've written code for this several times, but it's always been quite inelegant because of the need for the first command to be 'M'. This is the first time I've coded it in one line, which is why I'm so pleased with myself. Here it is:

d = ' '.join(['%s%d %d' % (['M', 'L'][i>0], x, y) for i, (x, y) in enumerate(coord_list)])

It uses all my favourite tricks, including list comprehensions, Boolean indices, and enumerate, as well as string formatting and join. It's probably not as efficient because it needs to test i>0 for every coordinate, but I don't care.

Comments (3)

iKlsR on April 30, 2012, 5:56 a.m.

ah. very neat. this will come in handy.

Anonymous on May 3, 2014, 5:17 a.m.

d = ' '.join([ '{0}{1[0]} {1[1]}'.format(*x) for x in zip('MLL', coord_list) ])

Peter on May 17, 2014, 3:44 p.m.

The code in the comment above will only work if there are three coordinates, but I want something that will work for an arbitrary number of coordinates.

Leave a comment

cancel reply