Some python console code
The python console is a great way to learn how the API works. For convenience C = bpy.context
and D = bpy.data
Using simply the default file
All collections and all objects in each.
>>> for col in D.collections:
... col.name, col.objects[:]
...
('Collection 1', [bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']])
or similarly
>>> for col in D.collections:
... col.name
... for o in col.objects:
... o.name
...
'Collection 1'
'Cube'
'Lamp'
'Camera'
Note the scene's top level or "master collection" is not listed above.
>>> C.scene.collection
bpy.data.collections['Master Collection']
Any objects in this collection? No, but if we link objects to it context.scene.collections.link(ob)
there could be.
>>> C.scene.collection.objects[:]
[]
Worth mentioning the all_objects
will recurse through and list all descendants (children, grandchildren, ...) collection's objects. In this case the child collection is "Collection 1"
>>> C.scene.collection.all_objects[:]
[bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']]
Iterate through master collection's child collections, and list their objects.
>>> for col in C.scene.collection.children:
... col.name, col.objects[:]
...
('Collection 1', [bpy.data.objects['Cube'], bpy.data.objects['Lamp'], bpy.data.objects['Camera']])