Add string at the end of list of string based on condition

Hello dear community,
I have a nested list inside dynamo, something like image attached. I am struggling finding a way to add string “LF” at the end of list of string. There should be condition embeded in this operation: add string only if existing string in the nested list is ending with " symbol. Do you have any suggestion what is the easiest way to achieve this? I have to keep the list structure of the original list. Also, condition should be checked only for @1 level, no need to go across all list levels.
Thank you

A loop in Python is the only way I can think of…

GPT just wrote this…so I haven’t tested it… but it should give you a start

def add_lf_to_nested_list_items(nested_list):
    for i in range(len(nested_list)):
        if isinstance(nested_list[i], list):  # If the item is a list, recurse
            add_lf_to_nested_list_items(nested_list[i])
        elif isinstance(nested_list[i], str) and nested_list[i].endswith('!'):  # Modify the condition as needed
            nested_list[i] += "LF"  # Add "LF" to the item that meets the condition

# Example usage
nested_list = ["Hello!", "World", ["Test!", "Example", ["Another Test!"]]]
add_lf_to_nested_list_items(nested_list)
print(nested_list)

Obvs you feed in your nested list instead of using the Hello World one :smiley:

and change print to OUT =

Isn’t it possible to filter the Elements first you want to add ‘LF’ to at the end of the string?

little variant with a recursive function


# Load the Python Standard and DesignScript Libraries
import sys
import clr

def add_end_symbol(value, end_char = "!", add_str="LF"):
    return value + add_str if value.endswith(end_char) else value


def nestedRecursFunc(lst, functoApply):
    newlst = list(lst)[:] # copy input list and convert it (if necessary)
    for idx, elem in enumerate(lst):
        if isinstance(elem, list) and len(elem) > 0:
            newlst[idx] = nestedRecursFunc(lst[idx], functoApply)
        elif isinstance(elem, list) and len(elem) == 0:
            newlst[idx] = []
        else:
            newlst[idx] = functoApply(lst[idx])

    return newlst
    
multi_NestedList = IN[0]

OUT = nestedRecursFunc(multi_NestedList, add_end_symbol)
2 Likes

No fancy code needed. Let Dynamo do the hard work (list management) for you.


Note: You cant just add a substring because the list structure would result in rank reduction. But you can remove a substring.

3 Likes

Thanks (for the tip to remember).
My first idea was not this.

Single-level lists are so much more practical
Sincerely
christian.stan

Thank you guys for helping out, I tested the python solution and it works as expected, thank you for sharing that.
I’ve also tested solution provided by Nick and marked that as solution as well. in case someone wants to do it just using dynamo. Actually, simple addition node works much better than all other string functions like concat which i’ve tried to use