28 Aug Admin
for <var> in <iterable>:
<statement(s)>
is a collection of objects—for example, a list or tuple. The in the loop body are denoted by indentation, as with all Python control structures, and are executed once for each item in . The loop variable takes on the value of the next element in each time through the loop.
Example–
a = ['apple', 'banana', 'mango']
for i in a:
print(i)
Output-
apple
banana
mango
In this example, <iterable> is the list a
, and <var> is the variable i
.
Each time through the loop, i
takes on a successive item in a
,
so print()
displays the values 'apple'
, 'banana'
, and 'mango'
, respectively.
A for
loop like this is the Pythonic way to process the items in an iterable.
Iterables
In Python, iterable means an object can be used in iteration. If an object is iterable, it can be passed to the built-in Python function iter()
, which returns something called an iterator. Yes, the terminology gets a bit repetitive.
Recent Comments