5

I was wondering how to reverse a list of lists in python. For example,

Original: list = [[1,2,3],[4,5,6],[7,8,9]] Output: new_list = [[7,8,9],[4,5,6],[1,2,3]]

Right now, I am trying this:

new_list = reversed(list)

However, this doesn't seem to work.

0

1 Answer 1

10
In [24]: L = [[1,2,3],[4,5,6],[7,8,9]]

In [25]: L[::-1]
Out[25]: [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
Sign up to request clarification or add additional context in comments.

5 Comments

Note for the record: reversed is lazily returning the reversed elements of the outer list; you need to iterate the value it returns, or wrap in a list constructor to convert it to a new list. Alternatively, you can reverse lists in place by calling .reverse(). The L[::-1] syntax is the canonical "return shallow copy in reverse order" approach though.
by "in place", it means the actual, original list is modified and reversed instead of returning a copy that has been reversed, correct? also, can you please point me to the documentation for [::-1]?
@oldboy: your understanding of in-place is correct. Also, here's the docs on slicing
thanks! let me see if i understand this correctly: since the start and end arguments are omitted, it signifies using the whole set of indices AND the step argument of -1 instructs the interpreter to begin at the end of the set?
@oldboy: yup. And in addition, in just this case, python is clever enough to know that start should be the last index and stop should be just before the first index. Thus your step of -1 goes from the last to the first index

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.