How to reverse list of string inside nested lists in python?

Viewed 198

I have a set of strings and a nested list of strings nested inside the list.

list1 = ['abc','def',[['abc','def']],['abc','def']].

and I want to get output similar shown below:

[['fed','cba'], [['fed','cba']], 'fed', 'cba']

when i used traditional method using built-in reverse() method and [::-1] as well. as shown below:

list1 = ['abc', 'def', [['abc', 'def']], ['abc', 'def']]
[x[::-1] for x in list1][::-1]
# and got output as [['def', 'abc'], [['abc', 'def']], 'fed', 'cba']

provide me some explanations on this?

2 Answers

Your problem is that you need to reverse the main list, every sublist in this list, and every string you meet on the way. You'd need some more general approach, using a recursion probably:

def deep_reverse(x):
    if isinstance(x, list):
        x = [deep_reverse(subx) for subx in x] # reverse every element
        x = x[::-1] # reverse the list itself
    elif isinstance(x, str):
        x = x[::-1]
    return x

list1 = ['abc','def',[['abc','def']],['abc','def']]
reversed_list1 = deep_reverse(list1) 
# [['fed', 'cba'], [['fed', 'cba']], 'fed', 'cba']

Somewhat entertaining solution is to turn to string the whole list, reverse it then evaluating it.

list1 = ['abc','def',[['abc','def']],['abc','def']]
str1 = str(list1)[::-1]

str1 = str1.replace('[', '[^[') # temporary
str1 = str1.replace(']', '[')
str1 = str1.replace('[^[', ']')

list2 = eval(str1)

Though you might want to be careful of edge cases where there are strings including [ or ].

Related