Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic reverse of list items in Python

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

like image 601
mrkafk Avatar asked Feb 25 '23 09:02

mrkafk


1 Answers

Extended slicing.

[x[::-1] for x in b]
like image 112
Ignacio Vazquez-Abrams Avatar answered Mar 03 '23 04:03

Ignacio Vazquez-Abrams