How to reverse the elements in a sublist?
<p>I'm trying to create a function that reverses the order of the elements in a list, and also reverses the elements in a sublist. for example:</p>

<p>For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]</p>

<p>I figured out how to reverse the order of one list, but I am having troubles with reversing the order of elements in a sublist. This is what I have so far:</p>

<pre><code>def deep_reverse(L)
    """ 
    assumes L is a list of lists whose elements are ints
    Mutates L such that it reverses its elements and also 
    reverses the order of the int elements in every element of L. 
    It does not return anything.
    """
    for i in reversed(L):
          print(i)
</code></pre>

<p>In the example above, my code would just print <code>[5,6,7], [3,4], [1,2]</code>, which is not what i'm trying to accomplish. It's just reversing the order of the lists, the not actual elements in the lists.</p>

<p>What should I add to the code so that it also reverses the order of the elements in a sublist?</p>

<p>[<strong>EDIT</strong>: my code <strong>needs</strong> to mutate the list; I don't want it just to print it, it actually needs to change the list.]</p>

<p>You could make this recursive, so it will work for arbitrarily deep nests.</p>

<p>something like (UNTESTED):</p>

<pre><code>def deep_reverse(L)
    """ 
    assumes L is a list of lists whose elements are ints
    Mutates L such that it reverses its elements and also 
    reverses the order of the int elements in every element of L. 
    It does not return anything.
    """
    for i in reversed(L):
          if len(i) &gt; 1:
              deep_reverse(i)
          else:
              print(i)
</code></pre>

python list python-3.x reverse sublist