Search code examples
pythonlistlist-comprehension

how to condense this code into one single line?


Given this array: arry = [[111,2],[3,4],9] I am trying to get this code segment condensed into a single line:


for index,item in enumerate(arry):
    if isinstance(item,list or np):
        for index2,item2 in enumerate(item):
            item[index2] = item2 *2
    else:
        arry[index]= item * 2
print(arry)

I tried this: print([[x*2 for x in y if isinstance(y,list)] for y in arry])

It works but its missing the else statement. Where should I insert the else statement?


Solution

  • You could try something like:

    print([[x*2 for x in y] if isinstance(y, list) else y * 2 for y in arry])
    

    Output:

    [[222, 4], [6, 8], 18]