List Contains Multiple Python

I’m using Python to see if a list contains multiple strings. It works great if I’m searching for multiple strings but errors if there is only 1 string. Is there something I can add to my python node to accommodate this?

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

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

list = IN[0]
out = []
for sublist in list:
        if True in sublist:
                out.append(True)
        else:
                out.append(False)
OUT = out

Easy fix: pass your search item as a list ( [search string]) if you have only one item.

correct method in my opinion is to check if it is a list (may be by counting the length of the list) if not make it a list.

reason for error : python is actually trying to find the sub list and in this case you don’t have a sub list.

5 Likes

Hi @Reed_Weinstock ,

What exactly do you mean by this?

If you are trying to determine if an item of list 1 also occurs in list 2 you could use the following approaches, no need for Python, that only makes it unnecessarily complex in my opinion in this case:


PS: Just to make sure you notice, in Approach A its important to swap the Items and List input from the way you have it now.

first check if the list is nested, then check True or false.

# Load the Python Standard and DesignScript Libraries
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

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

stringList = IN[0]

out = []

def is_nested_list(list2Check):   
    try:
          next(x for x in list2Check if isinstance(x,list)) 
    except StopIteration:
        return False
    return True
    
    
if is_nested_list(stringList):
    for sublist in stringList:
        if True in sublist:
                out.append(True)
        else:
                out.append(False)
else:
    if True in stringList:
            out.append(True)
    else:
            out.append(False)

"""
for sublist in list:
        if sublist.__contains__(True):
                out.append(True)
        else:
                out.append(False)
"""            
OUT = out

@Daan I’m working in 2020 and that version of dynamo doesn’t have the List.AnyTrue Node like newer versions.

I’m working in 2020 and that version of dynamo doesn’t have the List.AnyTrue Node like newer versions.

Clockwork (and other packages) do.

Or you can use List.Contains with true as an input to achieve similar results.

2 Likes

Yeah, or List.CountTrue folowed up by a code block containing X>0;

1 Like