for loop in python
- Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers.
- When we have a list of things to loop through, we can construct a definite loop using a for statement.
- We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
- The for loop is a generic iterator in python, it can step through the items in any ordered sequence or other iterable object.
- Python implements an iterator-based ‘for loop’. It is a type of ‘for loop’ that iterates over a list of items through an explicit or implicit iterator.
- The loop is introduced by the keyword ‘for’ which is followed by a random variable name which will contain the values supplied by the object.
- The Python for loop begins with a header line that specifies an assignment target, along with the object you want to step through.
The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:
friends = ['Amit', 'Aman', 'Anu']
for friend in friends:
print('Happy New Year:', friend)
- In Python terms, the variable friends is a list of three strings and the for loop goes through the list and executes the body once for each of the three strings in the list resulting in this output:
Happy New Year: Amit
Happy New Year: Aman
Happy New Year: Anu