1

I'm wondering if there is a way to write such a function with use of single list comprehension:

def sort_letters(word):
    lowers, uppers = [], []
    for letter in word:
            lowers.append(letter) if letter.islower() else uppers.append(letter)
    return lowers,uppers

I can write it like that:

def sort_letters2(word):
    return [x for x in word if x.islower()],[x for x in word if x.isupper()]

but it iterates twice through word. I'm curious how to sort letters within single list comprehension to get result similar to:

sort_letters("HaLLo")
(['a', 'o'], ['H', 'L', 'L'])

It doesn't necessary needs to look exactly like result up, but it should stick to idea of sorting lower case letters from upper. Is there way to write it like that?

Ethr
  • 431
  • 1
  • 3
  • 17
  • 2
    List comprehension isn't there to write one-liners, its there to comprehend a list - use an if statement – Sayse Oct 18 '19 at 08:52
  • Is there a particular reason why iterating twice through the list is bad? – tobias_k Oct 18 '19 at 08:53
  • 1
    If you want "a single list comprehension" you could do `[list(filter(f, word)) for f in (str.lower, str.upper)]`... – tobias_k Oct 18 '19 at 08:55
  • 2
    in your for loop `(lowers if letter.islower() else uppers).append(letter)` – Chris_Rands Oct 18 '19 at 08:57
  • @tobias_k but it is with two iteration – splash58 Oct 18 '19 at 09:25
  • @splash58 Yes, but of all the versions so far this is IMHO the clearest. (Also works with more than two subsets, although that will be even more iterations.) Hence my question, why two iterations is so bad. – tobias_k Oct 18 '19 at 10:10
  • Not bad, but if source is huge, it really could get a long time. I like more @Chris_Rands approach – splash58 Oct 18 '19 at 10:12

0 Answers0