iList in CPython scripts

Hi guys,

Does anyone know how to use Net Lists in CPython scripts? I regularly use them in IronPython scripts, where they work well.
The import statement seems fine, but when I try to use the Lists, they always appear empty.

Thanks in advance

Sure can.

from System.Collections.Generic import List
ilist = List[Element]()
print(type(ilist))

ilist as empty iList …

You can see you just declare what goes in the list. From there all the standard iList methods and properties work. Such as ilist.Add(Element)

Is this working for you in ‘CPython’ scripts ?

Both in Dynamo and pyRevit.

Thanks for the answer.

Could you try running this script in a pyRevit pushbutton and let me know if it works for you, please?
For me, it fails, but once I remove the Python3 shebang, it starts working again.

#! python3

from Autodesk.Revit.DB import FilteredElementCollector, ElementId
from System.Collections.Generic import List

doc = __revit__.ActiveUIDocument.Document

elements = FilteredElementCollector(doc).WhereElementIsNotElementType().ToElementIds()
ilist_elements = List[ElementId](elements)

print(len(elements) == len(ilist_elements))

Ran. Returns False.
The FilteredElementCollectorreturns an iList. So, there is no reason to then cast it to a iList. Thats just putting a list in an iList that is declared as a collection of ElementIds.

This works just fin and returns true.

#! python3

from Autodesk.Revit.DB import FilteredElementCollector, ElementId
from System.Collections.Generic import List

doc = __revit__.ActiveUIDocument.Document

elements = FilteredElementCollector(doc).WhereElementIsNotElementType().ToElementIds()
ilist_elements = List[ElementId]()
print(type(elements))
print(type(ilist_elements))
for e in elements:
	ilist_elements.Add(e)

print(len(elements) == len(ilist_elements))

You’ll see Iron python is returning the FilteredElemetnCollector as a iList (as it should).
Cpython is returning it as just a python list.
New one. Never look at it that way.
image

1 Like

And really the last line should be…
In IronPython:
print(elements.Count == ilist_elements.Count)

In CPython;
print(len(elements) == ilist_elements.Count)

…but both versions of python len will return the value for both a list and an iList.

I agree, but we technically shoud be able to cast an iList in a iList of ElementIds. Seeing this breaking the code caught my attention.

I was missing something.

This is the strange part, which I didn’t know about. Casting an entire Python list into an iList (in CPython) doesn’t work, while it works perfectly in IronPython.

I’ve tried the Add method, but it didn’t work in my previous tests, but it’s working now. I must have been doing something wrong earlier.

Thank you for your help Aaron !