4

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.

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Jenny
  • 43
  • 1
  • 1
  • 3

1 Answers1

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]]
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 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 `list`s in place by calling `.reverse()`. The `L[::-1]` syntax is the canonical "return shallow copy in reverse order" approach though. – ShadowRanger Nov 07 '15 at 03:54
  • 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 Aug 08 '21 at 21:03
  • @oldboy: your understanding of in-place is correct. Also, here's [the docs on slicing](https://docs.python.org/3/library/functions.html#slice) – inspectorG4dget Aug 09 '21 at 14:06
  • 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 Aug 10 '21 at 23:14
  • @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 – inspectorG4dget Aug 11 '21 at 11:34
  • awesome thanks man! – oldboy Aug 13 '21 at 00:13