0

I want to perform some actions within a huge list, which contains multiple lists, and within those multiple lists, they also have some lists, for example:

arr = [[[1, 2], 3], [2, 3, 4]]

How can I perform some actions with all the elements within these lists, for example +1 ? And the result will be :

[[[2, 3], 4], [3, 4, 5]]

I know I can use for to loop through every list, but sometimes those elements might be string or other types?

And I know I can check type() for every element inside the list do it recursively and perform some actions, but is there any simple way to solve this problem?


Too broad my ass

1 Answers1

1

A simple recursive routine can do that like:

Code:

def operate_on(data, operation):
    if isinstance(data, list):
        return [operate_on(x, operation) for x in data]
    else:
        return operation(data)

Test Code:

arr = [[[1, 2], 3], [2, 3, 4]]
print(operate_on(arr, lambda x: x + 1))

Results:

[[[2, 3], 4], [3, 4, 5]]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135