Python. List Exploring the types of elements in nested lists

Question. I immediately say why-homework. A list is given, with nested lists ( of unknown nesting depth). Write an algorithm that will go through all the nesting, get to the elements, and determine the type of each of them. The list will be, preferably, like this

a = [
    [
        [[1,2,3],["a","b","c"]],
        [[3,4,5],["d","e","f"]]
    ],
    [
        [[123,print,None],["aa","bb","cc"]],
        [[-10,3.14,"London"],[100,int,"qwerty"]]
    ]
]

My task is to determine the type of elements and perform some actions on them, depending on the type.

if element == int or float:
    print(element*2)
elif element == str:
    print(element*2)
elif element == None:
    print('none')
else:
    print('element is built in function')

But here's how to "get to the bottom" of the elements, nested lists - I'm slowing down. Obviously, by some recursive method, provided if element == list Please help the audience!

Author: MaxU, 2017-05-20

1 answers

Here is an example of a recursive implementation:

def f(element):
    if isinstance(element, (list, tuple, set)):
        for sub_element in element:
            f(sub_element)
    elif isinstance(element, (int, float)):
        print(element**2)
    elif isinstance(element, (str, bytes, bytearray)):
        print(element.upper())
    elif element is None:
        print("NONE")
    else:
        print("OTHER")

a = [
    [
        [[1,2,3],["a","b","c"]],
        [[3,4,5],["d","e","f"]]
    ],
    [
        [[123,print,None],["aa","bb","cc"]],
        [[-10,3.14,"London"],[100,int,"qwerty"]]
    ]
]

f(a)

>>>
1
4
9
A
B
C
9
16
25
D
E
F
15129
OTHER
NONE
AA
BB
CC
100
9.8596
LONDON
10000
OTHER
QWERTY
 1
Author: m9_psy, 2017-05-20 17:37:06