Home > Software design >  How to reverse each item in the nested list?
How to reverse each item in the nested list?

Time:01-31

Lists are used to store multiple items in a single variable. Lists are created using square brackets.

I want to reverse each item in the list of a list.

I tried reversed and [::1] method but it did not gave me desired output.

Here is my list
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]

I tried print(list1[::-1]) and reversed(list1) and got this output

output: [[8, 9, 10], 7, 6, [4, 5, 6], 3, 2, 1]

How could I get this output?

output: [[10, 9, 8], 7, 6, [6, 5, 4], 3, 2, 1]

CodePudding user response:

You can use a recursive function.

def revall(l):
    return [revall(x) if isinstance(x, list) else x for x in l[::-1]]
print(revall([1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]))

CodePudding user response:

Try this one:

list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
list1.reverse()
for sub_list in list1:
  if type(sub_list) is list:
        sub_list.reverse()
print(list1)
  • Related