0

I found a python "for loop" code online and its syntax differs from other codes. I would like to know about:

  1. Why is the 'key' in front of the for loop?
  2. Why is there an if statement inline?

CODE:

input = "codeforcode" 
freqDict = Counter(input)
freq1 = [ key for (key,count) in freqDict.items() if count==1]

Further, I would like to have web links to understand "for loop" more in-depth in python.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
nishanth
  • 11
  • 4

1 Answers1

1

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • yeah i understood .thanks – nishanth May 06 '19 at 07:19
  • @nishanth Great :) BTW, here in StackOverflow, if an answer helped you, you have the option of [upvoting the answer and/or marking it as accepted](https://stackoverflow.com/help/someone-answers). – Gino Mempin May 06 '19 at 09:47