# How to get average z location of selected vertices in python?

I want to get the average z location of selected vertices in python. And I want to select the vertices by their location using a range like (any vertices that lie in the range from 1 to 2 in the x axis).

• The average z location of selected vertices? – p2or Mar 5 '15 at 18:44
• I mean to get the sum of the z location of the selected vertex over their number. – Omar Emara Mar 5 '15 at 18:45
• Not sure what you want to achieve - I assume you need something like: z = [11, 1, 0] sum(z) / float(len(z)) right? – p2or Mar 5 '15 at 19:04

Bmesh module solutions for both tasks (edit-mode only so far):

import bpy
import bmesh

ob = bpy.context.object
me = ob.data
bm = bmesh.from_edit_mesh(me)

loc = [v.co.z for v in bm.verts if v.select]
if loc:
avg = sum(loc) / len(loc)
print(avg)

bpy.ops.mesh.select_all(action='DESELECT')

for v in bm.verts:
if v.co.x < 2 and v.co.x > 1:
v.select = True
bm.select_flush(True)

• this work thanks,but can you tell why you write that "if loc:". – Omar Emara Mar 6 '15 at 9:15
• @OmarAhmad just to test if loc list is not empty, see: stackoverflow.com/questions/53513/… – p2or Mar 6 '15 at 9:22
• @poor so if it is empty I can else: print("List is empty.") to inform the user to select something,thanks – Omar Emara Mar 6 '15 at 9:29
• As poor said, I want to check if the list is empty. If it was, an exception would be raised at the average location calculation (sum requires a non-empty sequence). You can handle the else-case too of course. If the code was surrounded in a function, you could also if not loc: return. – CodeManX Mar 8 '15 at 0:58

This is for calculating the average Z of the selected vertices :

import bpy

bpy.ops.object.mode_set(mode = 'OBJECT')
obj = bpy.context.active_object
s = i= 0
for v in obj.data.vertices:
if v.select :
s += v.co[2]
i += 1

bpy.ops.object.mode_set(mode = 'EDIT')
a = s/i
print(a)


for selecting use the same loop and do a test :

import bpy

bpy.ops.object.mode_set(mode = 'OBJECT')
obj = bpy.context.active_object
max = 2
min = 1
for v in obj.data.vertices:
if v.co[0] < max and v.co[0] > min :
v.select = True
bpy.ops.object.mode_set(mode = 'EDIT')

• This works too,thanks.but can you tell me what is "s = i= 0". – Omar Emara Mar 6 '15 at 9:16
• It's simply a shortcut that assigns 0 to both s and i - same as s=0 i=0 – sambler Mar 7 '15 at 5:46
• Using counter variables if quite un-pythonic. It's nicer and possibly faster to use list comprehensions. Note that mode switches can be expensive. They are required in the standard API however. The Bmesh module does not require mode changes, but it comes with an overhead. It's worth to compare performance on low and high resolution meshes. – CodeManX Mar 8 '15 at 1:02
• Possible divide by zero error here also, but helpful nonetheless. Thanks! – Nick Allan Jul 7 '20 at 15:44