0

i've been spending some time on this, but i'm still learning and haven't managed to do it. Well partialy i did, but i don't want the entering variable to be changed.

def changeit(element, value1, value2):
    if type(element) == list:
        for index, element2 in enumerate(element):
            if element2 == value1:
                element[index] = value2
            if type(element2) == list:
                changeit(element2, value1, value2)
            if value1 not in element:
                return element

def changelist(inputlist, value1, value2):
    for index, element in enumerate(inputlist):
        if type(element) == list:
            changeit(element, value1, value2)
        if element == value1:
            inputlist[index] = value2
    return inputlist

So the function should replace all value1 for value2. The desired output would be:

>>> k = [[[7]], 8]
>>> print(changelist(k, 7, 'a'))
[[['a']], 8]
>>> k
[[[7]], 8]

but so far i'm getting:

>>> k = [[[7]], 8]
>>> print(changelist((k,7,"x"))
[[['x']], 8]
>>> k
[[['x']], 8]

And i just can't find a way how to not change the entering list. Thanks!

A Student
  • 13
  • 3

1 Answers1

0
def replace(l, old, new):
    return [new if x == old else replace(x, old, new) if isinstance(x, list) else x for x in l]

Here's a recursive solution using list comprehensions. This is equivalent to

def replace(l, old, new):
    ret = []
    for x in l:
        if x == old:
            ret.append(new)
        elif isinstance(x, list):
            ret.append(replace(l, old, new))
        else:
            ret.append(x)
    return ret
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96