Home > OS >  Assigning only the first value in a list
Assigning only the first value in a list

Time:01-19

Given a dynamic list, that has potential to grow, is it possible to order the list such that no matter how it's otherwise sorted, a particular value is first?

list = ['bunny','cow','pig','apple','xerox']
list.sort()

ex. I want 'cow' to always be first on this list, and the rest can be ordered however. Or even better, 'cow' is always first and then they're alphabetically sorted after following that rule.

CodePudding user response:

Use a key function that orders that value first:

list.sort(key=lambda x: (0, x) if x == 'cow' else (1, x))

This will put cow first because 0 < 1 and everything else is sorted lexicographically.

CodePudding user response:

I would suggest create a class yourself that always use list[1:] for sort, but returns the appended list[0] sorted(list[1:]). Or, you can just create an individual parameter to store "cow", like list.First = "cow", list.Rest = ['bunny','pig','apple','xerox']

  • Related