Python for loop

"""
For loops iterate over lists
prints:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # You can use format() to interpolate formatted strings
    print("{} is a mammal".format(animal))
 
"""
"range(number)" returns an iterable of numbers
from zero to the given number
prints:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)
 
"""
"range(lower, upper)" returns an iterable of numbers
from the lower number to the upper number
prints:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print(i)
 
"""
"range(lower, upper, step)" returns an iterable of numbers
from the lower number to the upper number, while incrementing
by step. If step is not indicated, the default value is 1.
prints:
    4
    6
"""
for i in range(4, 8, 2):
    print(i)
"""

Iterable Dictionary

# Python offers a fundamental abstraction called the Iterable.
# An iterable is an object that can be treated as a sequence.
# The object returned the range function, is an iterable.
 
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)  # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.
 
# We can loop over it.
for i in our_iterable:
    print(i)  # Prints one, two, three
 
# However we cannot address elements by index.
our_iterable[1]  # Raises a TypeError
 
# An iterable is an object that knows how to create an iterator.
our_iterator = iter(our_iterable)
 
# Our iterator is an object that can remember the state as we traverse through it.
# We get the next object with "next()".
next(our_iterator)  # => "one"
 
# It maintains state as we iterate.
next(our_iterator)  # => "two"
next(our_iterator)  # => "three"
 
# After the iterator has returned all of its data, it gives you a StopIterator Exception
next(our_iterator)  # Raises StopIteration
 
# You can grab all the elements of an iterator by calling list() on it.
list(filled_dict.keys())  # => Returns ["one", "two", "three"]

Leave a Reply

Your email address will not be published. Required fields are marked *