How to run Python code if certain object is present in scene?

I'm trying to understand how to get Python and Blender to ask an Outliner if there is an "Alex_rig" object in the scene. If there is, then execute the code, if not finish.

There are several ways you can write Python that does what you want. If you want an exact match, in each of the examples, replace .startswith('Suzanne') with == 'Suzanne'

The easiest all rely on using the fact that any object has a name field.

You can create a list comprehension and see if there's anything in it:

object_list = [object for object in bpy.data.objects if object.name.startswith('Suzanne')]
if len(object_list):


That one's useful if you later want to do something with all of the objects of that name.

You can iterate over the objects until you find one

found = None
for object in bpy.data.objects:
print(object.name)
if object.name.startswith('Suzanne'):
found = object
break

if found:
print('Found one!')


That one's useful if you want to later use the first object you find with that name.

You can use a try/except block:

try:
found = bpy.data.objects['Suzanne']
except KeyError:
found = None

if found:
print('Found one!')


This one has the disadvantage that it only works for exact matches. Also, out of an abundance of caution it should not be used in performance critical areas of code.

import bpy

if 'Alex_rig' in bpy.context.scene.objects:
print('object exists')
else:
print('object does not exsist')


And if you need all the objects? (001,002, etc.)

Regex can be used:

import bpy
import re

r = re.compile('^Alex_rig[\.0-9]*$') if any(r.match(line) for line in bpy.context.scene.objects.keys()): print('object exists')  [\.0-9]* means any number (including 0) of numerals and dot, ^ and $ - the begin end the end of string.

https://regex101.com/r/jkqefS/1