FILE_PATH = 'l2-text'
f = open(FILE_PATH)
print ''.join([ t for t in f.read() if t.isalpha()])
f.close()
Question: Why is their a ‘t’ before the for loop t for t in f.read().
I understand the rest of the code except for that one bit.
If I try to remove it I get an error, so what does it do?
Thanks.
[t for t in f.read() if t.isalpha()]is a list comprehension. Basically, it takes the given iterable (f.read()) and forms a list by taking all the elements read by applying an optional filter (theifclause) and a mapping function (the part on the left of thefor).However, the mapping part is trivial here, this makes the syntax look a bit redundant: for each element
tgiven, it just adds the element value (t) to the output list. But more complex expressions are possible, for examplet*2 for t ...would duplicate all valid characters.