Python: Move specific lists within list, based on an element, at the end

Viewed 60

I have a list which contains other lists. Each element of this list contains 5 elements, like so:

requests = [['abc', 'def', 'abc.def@email.com', 'GROUP1', '000'],
           ['ghi', 'jkl', 'ghi,jkl@email.com', 'GROUP4', '111'],
           ['mno', 'pqr', 'mno.pqr@email.com', 'GROUP4', '222'],
           ['stu', 'vxy', 'stu.vxy@email.com', 'GROUP2', '333'],
           ['123', '456', '123.456@email.com', 'GROUP4', '444'],
           ['A12', 'B34', 'A12.B34f@email.com', 'GROUP3', '555']]

I would like to sort this list, in such a way that each list that contains an element equal to GROUP4, will be placed at the end of the list. So, the output would look like this:

requests = [['abc', 'def', 'abc.def@email.com', 'GROUP1', '000'],
           ['stu', 'vxy', 'stu.vxy@email.com', 'GROUP2', '333'],
           ['A12', 'B34', 'A12.B34f@email.com', 'GROUP3', '555'],
           ['ghi', 'jkl', 'ghi,jkl@email.com', 'GROUP4', '111'],
           ['mno', 'pqr', 'mno.pqr@email.com', 'GROUP4', '222'],
           ['123', '456', '123.456@email.com', 'GROUP4', '444'],]

I managed to sort them based on that specific element using:

requests.sort(key=lambda x: x[3])

But this just sorts them alphabetically, based on the 4th element. This won't work if a GROUP5 or GROUP6 is present, as those 2 will be the last elements.

Any ideas on how to do this?

Thank you very much!

2 Answers

You can change the lambda to check if the 4th item is 'GROUP4'

requests.sort(key=lambda x: x[3] == 'GROUP4')

If you want to sort the rest of the list as well use tuple in the lambda with two items, it will sort by 'GROUP4' first and then by lexicography order

requests.sort(key=lambda x: (x[3] == 'GROUP4', x[3]))

Move lists with GROUP4 at index [3] to the end by sorting by boolean.

requests.sort(key=lambda el: el[3] == "GROUP4")
Related