3

Python Challenge #2

Answer I found

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
gme
  • 41
  • 2
  • Thank you for the quick replies and your time, it's greatly appreciated. – gme Sep 24 '11 at 22:59
  • Welcome to StackOverflow. When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. [FAQ](http://stackoverflow.com/faq#howtoask). – johnsyweb Sep 24 '11 at 23:02

3 Answers3

3

This is a list comprehension, not a for-loop.

List comprehensions provide a concise way to create lists.

[t for t in f.read() if t.isalpha()]

This creates a list of all of the alpha characters in the file (f). You then join() them all together.

You now have a link to the documentation, which should help you comprehend comprehensions. It's tricky to search for things when you don't know what they're called!

Hope this helps.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
2

[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 (the if clause) and a mapping function (the part on the left of the for).

However, the mapping part is trivial here, this makes the syntax look a bit redundant: for each element t given, it just adds the element value (t) to the output list. But more complex expressions are possible, for example t*2 for t ... would duplicate all valid characters.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
0

note the following is also valid:

print ''.join(( t for t in f.read() if t.isalpha()))

instead of [ and ] you have ( and ) This specifies a generator instead of a list. generator comprehension

Community
  • 1
  • 1
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116