pub-3785248829033902 | Python: ??? filter() | - Big data with Python

| Python: ??? filter() |


A Generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.



Generators simplifies creation of iterators - please refer to Iterators for better understanding! A generator is a function that produces a sequence of results instead of a single value.

The (or one) benefit of generators is that because they deal with data one piece at a time, you can deal with large amounts of data; with lists, excessive memory requirements could become a problem.

Generators, just like lists, are iterable, so they can be used in the same ways. There are different ways to create a generator. You can use the parentheses syntax or you can use yield. Another interesting feature is that generators can be "infinite" -- iterators that don't stop.

The best way to learn new things is to take a practical approach of the things you want to learn. Let’s take a simple example and think or assume that you want to build Generator function in Python:

#Terminal command:

#1
fib = [0,1,1,2,3,5,8,13,21,34,55]
def Even(i):
        if i % 2 == 0:
            return True
        else:
           return False
result = list(filter(Even, fib))
print(result)

#2
cars = ['Tesla', 'Porsche', 'Ford', 'BMW', 'Audi', 'Mercedes-Benz', 'Chrysler']
def Small(i):
    return len(i) < 5

result2 = list(filter(Small, cars))
print(result2)


#result:

[0, 2, 8, 34]
['Ford', 'BMW', 'Audi']





Previous
Next Post »