'Understanding operators in for loops in Python 3
I have the following code as apart of IBM ETL cert as an exercise and do not understand how part of the code works.
Code:
def freqAll(self):
# split text into words
wordList = self.fmtText.split(' ')
# Create dictionary
freqMap = {}
for word in set(wordList): # use set to remove duplicates
freqMap[word] = wordList.count(word)
return freqMap
In the block that creates the dictionary the code in the for loop says
for word in set(wordList):
how does python know that "word" is in the word list? There is no part of the code that defines "word" as anything...
Solution 1:[1]
For loops in Python work differently to those in most other languages. Instead of incrementing a counter, they loop over an "iterable", which can be a list, a set, a range, or many other elements.
For each iteration of the loop, Python asks the term to the right of the in for the next value, and binds that to the variable name on the left of it. Therefore, that word can be any variable name. It keeps asking for the next value to bind to the variable until the thing on the right runs out of items. At that point, Python ends the loop and continues on with the rest of the code.
Solution 2:[2]
when you type for word in set(wordList): it is implicitly doing the check.
word is the variable that stores the word that is being read at that moment, and wordList is the list where you have saved all the words that you are going to read
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Miguel Guthridge |
| Solution 2 |
