It's called a List Comprehension.
A list comprehension consists of brackets containing an expression
followed by a for
clause, then zero or more for
or if
clauses. The
result will be a new list resulting from evaluating the expression in
the context of the for and if clauses which follow it. For example,
this listcomp combines the elements of two lists if they are not
equal:
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
That for
loop you have
[ key for (key,count) in freqDict.items() if count==1]
is equivalent to:
keys = []
for key, count in freqDict.items():
if count == 1:
keys.append(key)
The regular for
loop that you probably know is still valid in Python, nothing is changed there. Using list comprehensions "provides a more concise way to create lists" as the for
loop/s and the if
condition are all put into a single line, and also, you don't need to create a temporary variable for storing the resulting list.