I am trying to follow the python code below (Finding middle point (midpoint) of line in QGIS?) to create midpoints of line segments in QGIS 1.8. I am receiving errors executing the code. Unfortunately, I have no background in Python.

>>> def pair(list):
...    '''Iterate over pairs in a list '''
...     for i in range(1, len(list)):
  File "<input>", line 3
**for i in range(1, len(list)):**
IndentationError: unexpected indent**

another error:

>>>         yield list[i-1], list[i]
**File "<input>", line 1
yield list[i-1], list[i]
IndentationError: unexpected indent**

and finally

**Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'mylayer' is not defined**

Pyhton code:

def mid(pt1, pt2):
   x = (pt1.x() + pt2.x())/2
   y = (pt1.y() + pt2.y())/2
   return QgsPoint(x,y)

def pair(list):
    '''Iterate over pairs in a list '''
    for i in range(1, len(list)):
        yield list[i-1], list[i]

def create_geometry(point,pr):
    # create geometry record 
    seg = QgsFeature()
    pr.addFeatures( [seg] )

# memory layer
pt_layer = QgsVectorLayer("Point", "midpoint", "memory")
pr = pt_layer.dataProvider()

for elem in mylayer.selectedFeatures():
    line = elem.geometry()
    for seg_start, seg_end in pair(line.asPolyline()):
        line_start = QgsPoint(seg_start)
        line_end = QgsPoint(seg_end)
        # midpoint 
        midpt= mid(line_start, line_end)
        # add midpoint point to layer

  • look at Dive into Python:indenting code
    – gene
    Sep 27, 2014 at 7:49
  • '''Iterate over pairs in a list '''and for i in range(1, len(list)):with the same indentation
    – gene
    Sep 27, 2014 at 7:57
  • 1
    If you copy/paste an incorrectly indented python code to QGIS Python Console, you get IndentationError for each improperly indented lines. Oct 14, 2018 at 22:52

1 Answer 1


I did a quick check and your indentation is a bit random. I am actually surprised you didn't get more indentation error messages.

Indentation is critical in Python because it doesn't use brackets to denote the start and end of loops etc, but uses whitespace (a feature loved and loathed in equal measure). The most common convention is four spaces or one tab (but not mixed!). In the first error, you have five spaces in front of 'for'. The second error has four spaces but follows a code block with three spaces as the indent (def mid block).

I recommend that you copy your code into an ide (e.g. PyCharm) and systematically set the indentations to be consistent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.