Python output items based on sublist lengths

Hi everyone,

I am trying to output values from a list based on the length of sub-lists through Python. I am a Python beginner and I am struggling with what I want to accomplish.
The output I want to achieve is inside the red rectangle but I am getting something different:

My Python code:

# Enable Python support and load DesignScript library
import clr
#clr.AddReference('ProtoGeometry')
#from Autodesk.DesignScript.Geometry import *

# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import * 

# Import RevitServices
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

# The inputs to this node will be stored as a list in the IN variables.
dataEnteringNode = IN


goals = IN[0]
pattern = IN[1]
in_range = []
out_range = []
length_values = 0
index = 0

# Place your code below this line

# Loop through the sublists
for sublist in pattern:
    length_sublist = len(sublist)
    # Check how many items the sub-list has
    for goal in range(length_sublist):
        length_goals = len(goals)
        # check if the sublist length is bigger then the list I want
        # To show and output "out of range"
        if length_sublist > length_goals:
            out_range.append("item out of range")
            index = length_goals
        # Append the goals items into a new list
        else:
            in_range.append(goals[goal])
# Put everything together
in_range.insert(index, out_range)

# Assign your output to the OUT variable.
OUT = in_range

I was able to mimic the desired output with Python alone (not in Dynamo environment) though by making a dictionary and looping through the values of that dictionary. I am having troubles applying a similar approach when I use Python within Dynamo.

I am not asking for direct code correction but rather for pointing the right way to achieve what I want based on the given inputs.
Any help is appreciated
Thanks :slight_smile:

test_2.dyn (17.7 KB)

Hi @JFK,
Try this:

def toList(input):
	if hasattr(input,"__iter__"): return input
	else: return [input]
	
goals = toList(IN[0])
patterns = toList(IN[1])
out = []

for pattern in patterns:
	temp = []
	if len(pattern)>len(goals):
		for i in pattern:
			temp.append("Item out of range")
	else:
		for i in range(len(pattern)):
			temp.append(goals[i])
	out.append(temp)

OUT = out
1 Like

Hi @AmolShah,

Indeed it works, the output is what I am looking for.
I don’t understand fully the first part of your code (function definition) since I still don’t grasp how functions in python work and the hasattr() method is completely unknown to me.
I will continue to dig into python so the code gets a bit easier to understand.

Thanks for your help.

1 Like

Determine if an object is iterable. To determine if an input data is a list.

2 Likes