1

Im trying to add a prefix to a list of strings in Python. The list of strings may contain multiple levels of nested lists.

Is there a way to loop through this list (and its nested lists), while keeping the structure?

nested for-loops became unreadable very quick, and did not seem to be the right approach..

list = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee']]]

for i in list:
        if isinstance(i, list):
                for a in i:
                        a = prefix + a
                        #add more layers of for loops
        else:
                i = prefix + i

desired outcome:

prefix = "#"
newlist = ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]

Thanks in advance!

1

4 Answers 4

2

You could write a simple recursive function

def apply_prefix(l, prefix):
    # Base Case
    if isinstance(l, str):
        return prefix + l
    # Recursive Case
    else:
        return [apply_prefix(i, prefix) for i in l]


l = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee',]]]

print(apply_prefix(l, "#"))
# ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]
Sign up to request clarification or add additional context in comments.

Comments

1

This will use recursion:

a = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee',]]]


def insert_symbol(structure, symbol='#'):
    if isinstance(structure, list):
        return [insert_symbol(sub_structure) for sub_structure in structure]
    else:
        return symbol + structure

print(insert_symbol(a))

>>> ['#a', '#b', ['#C', '#C'], '#d', ['#E', ['#Ee', '#Ee']]]

Comments

0

You can use a recursive code like this!, Try it, and if you have questions you can ask me

def add_prefix(input_list):
    changed_list = []
    for elem in input_list:
        if isinstance(elem, list):
            elem = add_prefix(elem)
            changed_list.append(elem)
        else:
            elem = "#" + elem
            changed_list.append(elem)
    return changed_list

Comments

0

Maybe you can use a function to do it recursively.

list_example = ['a', 'b', ['C', 'C'], 'd', ['E', ['Ee', 'Ee']]]

def add_prefix(p_list, prefix):
    for idx in range(len(p_list)):
        if isinstance(p_list[idx], list):
            p_list[idx] = add_prefix(p_list[idx], prefix)
        else:
            p_list[idx] = prefix + p_list[idx]
    return p_list

add_prefix(list_example, '#')

edit: I see now someone has posted the almost same thing.

btw. it is considered bad practice to name a list list, since it is also a typename in python. Might result in unwanted behaviour

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.