Search code examples
python-3.xfunctionreturnlist-comprehension

Transform a "multiple line" - function into a "one line" - function


I try to transform a function that consists of multiple lines into a function that only consists of one line.

The multiple-line function looks like this:

text =  “Here is a tiny example.”

def add_text_to_list(text):
             new_list = []
             split_text = text.splitlines() #split words in text and change type from “str” to “list”
             for line in split_text:
                 cleared_line = line.strip() #each line of split_text is getting stripped
                 if cleared_line:
                     new_list.append(cleared_line)
             return new_list

I 100% understand how this function works and what it does, yet I have trouble implementing this into a valid “oneliner”. I also know that I need to come up with a list comprehension. What I'm trying to do is this (in chronological order):

1. split words of text with text.splitlines()
2. strip lines of text.splitlines with line.strip()
3. return modified text after both of these steps

The best I came up with:

def one_line_version(text):
  return [line.strip() for line in text.splitlines()] #step 1 is missing

I appreciate any kind of help.

Edit: Thanks @Tenfrow!


Solution

  • You forgot about if in the list comprehension

    def add_text_to_list(text):
        return [line.strip() for line in text.splitlines() if line.strip()]