Home > OS >  Change all strings in list of lists but the last element
Change all strings in list of lists but the last element

Time:06-05

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?

CodePudding user response:

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'], []]

CodePudding user response:

Map str.lower until the penultimate element and unpack the map object in a list inside a comprehension

# map str.lower to every element until the last word
# and unpack it in a list along with the last word
[[*map(str.lower, words[:-1]), words[-1]] for words in lists]

If a sub-list can be empty (as in wjandrea's example), then add a conditional check (although this is far less readable and downright bad code)

[[*map(str.lower, words[:-1]), words[-1]] if words else [] for words in lists]
  • Related