Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the elements in a sublist?

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:

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

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:

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)

In the example above, my code would just print [5,6,7], [3,4], [1,2], 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.

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

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

like image 824
gp0478 Avatar asked Mar 11 '23 00:03

gp0478


2 Answers

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.

Then do exactly those two things:

L.reverse()
for sublist in L:
    sublist.reverse()

Full demo because you seem to be confused about what your function is supposed to do and how to test it:

>>> 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.
        """
        L.reverse()
        for sublist in L:
            sublist.reverse()

>>> L = [[1, 2], [3, 4], [5, 6, 7]]
>>> deep_reverse(L)
>>> print(L)
[[7, 6, 5], [4, 3], [2, 1]]
like image 36
Stefan Pochmann Avatar answered Mar 21 '23 08:03

Stefan Pochmann


[sublist[::-1] for sublist in to_reverse[::-1]]

List comprehension works here. [::-1] is basically the same as reversed, but does not modify the list.

EDIT:

As pointed out below, reversed doesn't modify the list. It returns a listreverseiterator object

More Edit:

If you want a solution for lists of arbitrary depth, try:

def deep_reverse(to_reverse):
    if isinstance(to_reverse, list):
        return list(map(deep_reverse, to_reverse[::-1]))
    else:
        return to_reverse

Even more Edit:

To mutate a list in a function:

L[:] = new_list 

Will modify the list in place.

like image 87
Patrick Haugh Avatar answered Mar 21 '23 06:03

Patrick Haugh