iteration python code example
Example 1: python return iteration number of for loop
# Basic syntax:
for iteration, item in enumerate(iteratable_object):
print(iteration)
# Where:
# - item is the current element in the iteratable_object
# - iteration is the iteration number/count for the current iteration
# Basic syntax using list comprehension:
[iteration for iteration, item in enumerate(iteratable_object)]
# Example usage:
your_list = ["a", "b", "c", "d"]
for iteration,item in enumerate(your_list):
(iteration, item) # Return tuples of iteration, item
--> (0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
[iteration for iteration, item in enumerate(your_list)]
--> [0, 1, 2, 3]
Example 2: what is iteration in python
# Iteration is the execution of a statement repeatedly and without
# making any errors.
Example 3: how to use iteration in python
>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
... print(i)
...
foo
bar
baz
Example 4: how to use iteration in python
for i = 1 to 10
<loop body>
Example 5: python iterator
pies = ["cherry", "apple", "pumpkin", "pecan"]
iterator = iter(pies)
print(next(iterator))
#prints "cherry" because it's the current one being iterated over
Example 6: how to use iteration in python
n = 5
while n > 0:
print n
n = n-1
print 'Blastoff!'