1

I have a multidimensional list which is basically a list of strings nested within a list. I want a list to be reversed and also the list items within the list to be reverse and further the strings in the list should also be reversed.

Ex: I have a list

[
    ['123', '456', '789'], 
    ['234', '567', '890'], 
    ['345', '678', '901']
]

I want the result to be

[
    ['109', '876', '543'],
    ['098', '765', '432'],
    ['987', '654', '321']
]

I've already tried the code, It's working. But can we simplify further using list comprehension.

Below is the code which I tried.

old = [['123', '456', '789'], ['234', '567', '890'], ['345', '678', '901']]
new = [];
for x in old[::-1]:
    z = [];
    for y in x:
        z.insert(0, y[::-1])
    new.append(z)
print(new)

Input

[['123', '456', '789'], ['234', '567', '890'], ['345', '678', '901']]

Output

[['109', '876', '543'], ['098', '765', '432'], ['987', '654', '321']]
1
  • you don't need the semicolons at the ends of the line :) Commented Dec 21, 2018 at 9:49

1 Answer 1

5

you want this one-liner:

result = [[x[::-1] for x in reversed(y)] for y in reversed(lst)]

notes:

  • reversed(lst) is faster than lst[::-1] because it doesn't create a new list, it just iterates backwards (in that case it works because the length is known).
  • x[::-1] is left as-is because it's much faster than "".join(reversed(x)) to reverse a string as a string.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I was able to modify it after your solution result = [[x[::-1] for x in y[::-1]] for y in lst[::-1]]
yeah works too, but reversed is better [::-1] creates a new list (allocation, copy...) that you don't need.

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.