Search code examples
pythonlistlist-comprehension

Change all strings in list of lists but the last element


I am trying to use list comprehension to create a new list of lists of strings in which all strings but the last will be lowercased. This would be the critical line, but it lowercase all strings:

[[word.lower() for word in words] for words in lists]

If I do this:

[[word.lower() for word in words[:-1]] for words in lists]

the last element is omitted.

In general, if the list is rather long, is comprehension the best/fastest approach?


Solution

  • You can simply add back the last slice:

    [[word.lower() for word in words[:-1]] + words[-1:] for words in lists]
    

    For example, with

    lists = [["FOO", "BAR", "BAZ"], ["QUX"], []]
    

    the output is:

    [['foo', 'bar', 'BAZ'], ['QUX'], []]