let' work through another common application of list comprehensions to explore them in more detail recall that the file object has readlines method that loads the file into list of line strings all at oncef open('script py'lines readlines(lines ['import sys\ ''print(sys path)\ '' \ ''print( * )\ 'this worksbut the lines in the result all include the newline character (\nat the end for many programsthe newline character gets in the way--we have to be careful to avoid double-spacing when printingand so on it would be nice if we could get rid of these newlines all at oncewouldn' itanytime we start thinking about performing an operation on each item in sequencewe're in the realm of list comprehensions for exampleassuming the variable lines is as it was in the prior interactionthe following code does the job by running each line in the list through the string rstrip method to remove whitespace on the right side ( line[:- slice would worktoobut only if we can be sure all lines are properly \ terminatedand this may not always be the case for the last line in file)lines [line rstrip(for line in lineslines ['import sys''print(sys path)'' ''print( * )'this works as planned because list comprehensions are an iteration context just like for loop statementsthoughwe don' even have to open the file ahead of time if we open it inside the expressionthe list comprehension will automatically use the iteration protocol we met earlier in this that isit will read one line from the file at time by calling the file' next handler methodrun the line through the rstrip expressionand add it to the result list againwe get what we ask for--the rstrip result of linefor every line in the filelines [line rstrip(for line in open('script py')lines ['import sys''print(sys path)'' ''print( * )'this expression does lot implicitlybut we're getting lot of work for free here-python scans the file by lines and builds list of operation results automatically it' also an efficient way to code this operationbecause most of this work is done inside the python interpreterit may be faster than an equivalent for statementand won' load file into memory all at once like some other techniques againespecially for large filesthe advantages of list comprehensions can be significant besides their efficiencylist comprehensions are also remarkably expressive in our examplewe can run any string operation on file' lines as we iterate to illustratehere' the list comprehension equivalent to the file iterator uppercase example we met earlieralong with few other representative operations iterations and comprehensions