Bram G
Bram G

Reputation: 23

Looping through list and nested lists in python

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!

Upvotes: 1

Views: 133

Answers (4)

Cohan
Cohan

Reputation: 4544

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']]]

Upvotes: 2

marcos
marcos

Reputation: 4510

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']]]

Upvotes: 1

San
San

Reputation: 1

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

Upvotes: 0

Andrex
Andrex

Reputation: 682

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

Upvotes: 0

Related Questions