Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Challenge #2 - For loop problem

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.

like image 507
gme Avatar asked Jun 30 '26 11:06

gme


2 Answers

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.

like image 139
Johnsyweb Avatar answered Jul 03 '26 01:07

Johnsyweb


[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.

like image 38
Alexander Gessler Avatar answered Jul 03 '26 01:07

Alexander Gessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!