2

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?

1
  • Your code snippet simply reverses each element of list1. But not recursively. Commented Jun 9, 2021 at 7:48

2 Answers 2

7

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, and beat me by a minute or two :)
0

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 ].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.