Python iter() Built in Function

The iter() function returns an iterator object for a given iterable or a callable object. An iterator is an object that can be iterated over, meaning that you can traverse through all the values.

Here are some examples of using the iter() function:

# Example 1: Get an iterator from a list
fruits = ["apple", "banana", "cherry"]
fruits_iter = iter(fruits)
print(next(fruits_iter))
# apple
print(next(fruits_iter)) # banana
print(next(fruits_iter)) # cherry


# Example 2: Get an iterator from a custom class
class Counter:
    def __init__(self, max):
        self.max = max


    def __iter__(self):
        self.num = 0
        return self


    def __next__(self):
        if self.num < self.max:
            self.num += 1
            return self.num
        else:
            raise StopIteration


counter = Counter(5)
counter_iter = iter(counter)
print(next(counter_iter))
# 1
print(next(counter_iter)) # 2
print(next(counter_iter)) # 3
print(next(counter_iter)) # 4
print(next(counter_iter)) # 5


# Example 3: Get an iterator from a callable object and a sentinel value
def get_random():
    import random
    return random.randint(0,9)


random_iter = iter(get_random, 5) # stop when get_random returns 5
for num in random_iter:
    print(num)
# print random numbers until 5 is encountered

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Python The _ Operator

Python bool() Built in Function

Python Printing Readable Results

Python One Liner Functions