Search code examples
pythonlistreverse

How to reverse each item in the nested list?


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]


Solution

  • 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)