Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Python Scripting

Create Blender Meshes with Python: Vertices, Faces and bmesh

Build Blender geometry from code: create a mesh from vertices and faces, use from_pydata and bmesh, add materials and arrange many objects in a loop.

The real power of scripting is making things you would never place by hand: a spiral staircase of 200 steps, a grid of 10,000 cubes, a terrain from a height formula. This lesson shows how a mesh is built from vertices, edges and faces, how to create one in Blender with Python, and how to generate patterns of objects.

Blender is not available on the site, so the Blender code is read-only. Each section pairs it with a runnable Python stand-in that builds the same data (lists of vertices and faces) and checks it, so you can test your maths and indexing before running anything in Blender. See the bpy basics for bpy.data and bpy.context.

What a mesh is

A mesh is three lists:

  • Vertices: points (x, y, z).
  • Edges: pairs of vertex indices.
  • Faces: lists of vertex indices (3 for a triangle, 4 for a quad, more for an n-gon). The order matters: counterclockwise as seen from outside means the face normal points outward.

A cube has 8 vertices, 12 edges and 6 faces. Euler's formula for closed shapes without holes: V - E + F = 2.

Creating a mesh with from_pydata

Python
import bpy

verts = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 1.5)]
faces = [(0, 1, 2, 3), (0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]   # a pyramid

mesh = bpy.data.meshes.new("Pyramid")
mesh.from_pydata(verts, [], faces)      # edges are derived from faces when the list is empty
mesh.update()
mesh.validate()                          # fixes some errors and returns True if it changed anything

obj = bpy.data.objects.new("Pyramid", mesh)
bpy.context.collection.objects.link(obj)

Note: the mesh data block (bpy.data.meshes) holds the shape, and the object (bpy.data.objects) holds location, rotation and scale and points at the mesh. Many objects can share one mesh (linked duplicates, Alt+D).

The stand-in below builds the same pyramid and checks the data: face indices must exist, and each edge should be shared by exactly two faces in a closed mesh.

Python Stand-in: build and check a pyramid mesh

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The bmesh module

bmesh is a lower-level, faster way to create and edit geometry with full topology access (it works like Edit Mode). Typical flow: create a BMesh, add geometry, write it into a mesh, free it.

Python
import bpy
import bmesh

mesh = bpy.data.meshes.new("Grid")
bm = bmesh.new()

n = 10
verts = [[bm.verts.new((x, y, 0.0)) for y in range(n)] for x in range(n)]
for x in range(n - 1):
    for y in range(n - 1):
        bm.faces.new((verts[x][y], verts[x + 1][y], verts[x + 1][y + 1], verts[x][y + 1]))

bm.to_mesh(mesh)
bm.free()                                   # always free a BMesh you created with bmesh.new()

obj = bpy.data.objects.new("Grid", mesh)
bpy.context.collection.objects.link(obj)

For an existing object in Edit Mode, use bmesh.from_edit_mesh(obj.data) and call bmesh.update_edit_mesh(obj.data) at the end instead of to_mesh and free. Operators in bmesh.ops perform bevel, extrude, subdivide, remove doubles and so on.

Procedural terrain: heights from a formula

Generating geometry means turning a formula into vertex positions and then connecting them with faces. The stand-in creates a small wave terrain and the face index list for a grid. You can reuse the functions in a Blender script unchanged (only the final from_pydata call needs bpy).

Python Stand-in: grid terrain vertices and quad faces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For an n by n grid you always get n*n vertices and (n-1)*(n-1) faces: a good sanity check when your own script produces strange results.

Arranging objects in a loop

You can place copies of an existing object in patterns, for instance a spiral:

Python
import bpy, math

source = bpy.data.objects["Cube"]
for i in range(30):
    angle = i * 0.5
    radius = 1 + i * 0.15
    copy = source.copy()                      # linked copy shares the same mesh data
    copy.location = (radius * math.cos(angle), radius * math.sin(angle), i * 0.1)
    copy.rotation_euler.z = angle
    bpy.context.collection.objects.link(copy)

source.copy() copies the object but shares the mesh. For an independent mesh use copy.data = source.data.copy(). For thousands of copies, prefer collection instances or the Geometry Nodes modifier (see Geometry Nodes basics), because they cost far less memory.

Python Stand-in: spiral positions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Materials from code

Python
import bpy

mat = bpy.data.materials.new("Red")
mat.use_nodes = True                                       # needed in Blender 4.x and older to get nodes
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (0.8, 0.05, 0.05, 1.0)
bsdf.inputs["Roughness"].default_value = 0.35

obj = bpy.context.active_object
if obj.data.materials:
    obj.data.materials[0] = mat
else:
    obj.data.materials.append(mat)

Newer versions of Blender create node trees by default; setting use_nodes is still harmless, though newer releases mark it deprecated. Check the Python API reference for your version.

Cleaning up and performance

  • Remove data you created if the script fails: bpy.data.objects.remove(obj). Orphan meshes are removed on save and reload, or via File > Clean Up > Purge Unused Data.
  • Do not call bpy.ops in big loops: each call updates the scene. Build a list in Python and create objects with the data API.
  • Setting mesh.update() and mesh.validate() once at the end is faster than doing it per vertex.
  • Run a long script on a small sample first, to see it works.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the three basic lists that define a mesh?

    Vertices are points, edges connect two vertices and faces connect three or more.
  2. 2. What must you do after bmesh.new() and bm.to_mesh(mesh)?

    A BMesh created with bmesh.new() must be freed to release its memory.
  3. 3. A 6 x 6 vertex grid has how many quad faces?

    (6 - 1) x (6 - 1) = 25 quads.
  4. 4. Why do new objects from bpy.data.objects.new not appear in the viewport?

    Linking the object into a collection of the scene, e.g. bpy.context.collection.objects.link(obj), makes it part of the scene.

Summary

  • A mesh is vertices, edges and faces; from_pydata and bmesh create them from code.
  • Always link new objects to a collection and free BMesh objects.
  • Prefer the data API to operators in loops; consider instances or Geometry Nodes for huge counts.
  • Test your index maths in plain Python first.

Next: Vectors, Matrices and mathutils