Say I have a list object occupied with both numbers and strings. If I want to retrieve the first string item with the highest alphabetical precedence, how would I do so?
Here is an example attempt which is clearly incorrect, but corrections as to what needs to be changed in order for it to achieve the desired result would be greatly appreciated:
lst = [12, 4, 2, 15, 3, 'ALLIGATOR', 'BEAR', 'ANTEATER', 'DOG', 'CAT']
lst.sort()
for i in lst:
if i[0] == "A":
answer = i
print(answer)
Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
If you're sorting by first element of nested list, you can simply use list. sort() method.
First use a generator expression to filter out non-strings, and then use min()
to select the string with the highest alphabetical presence:
>>> min(x for x in lst if isinstance(x, str))
'ALLIGATOR
IIUC you could use isinstance
to get sublist of your original list with only strings, then with sorted
get first element by alphabetical sorting:
sub_lst = [i for i in lst if isinstance(i, str)]
result = sorted(sub_lst)[0]
print(sub_lst)
['ALLIGATOR', 'BEAR', 'ANTEATER', 'DOG', 'CAT']
print(result)
'ALLIGATOR'
Or you could use min
as @TigerhawkT3 suggested in the comment:
print(min(sub_lst))
'ALLIGATOR'
Another way is to filter the main list lst
from intergers using filter
built-in method:
>>> min(filter(lambda s:isinstance(s, str), lst))
'ALLIGATOR'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With