The FOR loop in Python can do a few more tricks then it can in other languages, and works in slightly different ways in what it pulls out depending on what object type you are looping on.
Looping on a String
x = “text”
for c in x:
print c
The Result:
t
e
x
t
The for loop loops over each character in the string and puts it in the c variable.
Looping on a list or tuple
Looping on a list or tuple is pretty standard, but can be done in two ways. You can go by the index number or you can let Python handle it.
Classic For Loop
myList = ["a","b","c"]
for i in range(0,len(myList)):
print myList[i]
Foreach Style
myList = ["a","b","c"]
for item in myList:
print item
Both of these have the same result, and just print out each list element.
Looping on a dictionary
Looping on a dictionary is a little different since we have a key for each element. When it is looped on the key is what is given, and if you want to access the actual value you need to use the key in the dictionary to get it out.
myDict = {}
myDict["first"] = “a”
myDict["second"] = “b”
myDict["third"] = “c”
for key in myDict:
print myDict[key]