Printing within list comprehension in Python
function, list, list-comprehension, printing, python
Solution
No statements can appear in Python expressions. `print` is one kind of statement in Python 2, and list comprehensions are one kind of expression. Impossible. Neither can you, for example, put a `global` statement in an index expression.
Note that in Python 2, you can put
from __future__ import print_function
to have `print()` treated as a function instead (as it is in Python 3).
Problem
I am getting a syntax error when executing the following code. I want to print within a list comprehension. As you see, I tried a different approach (commented out line) by using print(). But I think this syntax is supported in Python 3 as earlier versions of Python treat print as a statement. ``` 1 import sys 2 import nltk 3 import csv 4 from prettytable import PrettyTable 5 CSV_FILE = sys.argv[1] 6 # Handle any known abbreviations, # strip off common suffixes, etc. 7 transforms = [(', Inc.', ''), (', Inc', ''), (', LLC', ''), (', LLP', '')] 8 csvReader = csv.DictReader(open(CSV_FILE), delimiter=',', quotechar='"') 9 contacts = [row for row in csvReader] 10 companies = [c['Company'].strip() for c in contacts if c['Company'].strip() != ''] 11 for i in range(len(companies)): 12 for transform in transforms: 13 companies[i] = companies[i].replace(*transform) 14 #fields=['Company', 'Freq'] 15 #pt = PrettyTable(fields=fields) 16 #pt.set_field_align('Company', 'l') 17 fdist = nltk.FreqDist(companies) 18 #[pt.add_row([company, freq]) for (company, freq) in fdist.items() if freq > 1] 19 #[print("["+company+","+freq+"]") for (company, freq) in fdist.items() if freq > 1] 20 [print company for (company, freq) in fdist.items() if freq > 1] 21 #pt.printt() ~ ```