4
>>> b=[('spam',0), ('eggs',1)]
>>> [reversed(x) for x in b]
[<reversed object at 0x7fbf07de7090>, <reversed object at 0x7fbf07de70d0>]

Bummer. I expected to get a list of reversed tuples!

Sure I can do:

>>> [tuple(reversed(x)) for x in b]
[(0, 'spam'), (1, 'eggs')]

But I hoped for something generic? Smth that when being handed over a list of tuples, returns a list of reversed tuples, and when handed over a list of lists, returns a list of reversed lists.

Sure, an ugly hack with isinstance() is always available but I kind of hoped avoiding going that route.

mrkafk
  • 617
  • 1
  • 5
  • 4

2 Answers2

8

Extended slicing.

[x[::-1] for x in b]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

If you only need depth of one, try [x[::-1] for x in mylist]. Otherwise just make a recursive function like

import collections
def recursive_reversed(seq):
    if isinstance(seq, collections.Sequence):
        return [recursive_reversed(x) for x in reversed(seq)]
    return seq

That function actually converts all of the sequences to lists, but you get the gist, I hope.

Shadikka
  • 4,116
  • 2
  • 16
  • 19