Posts

Showing posts with the label Python_Advanced Topics

learnpython24-(Python Iterators)

  Python Iterators Iterators are objects that can be iterated upon. In this tutorial, you will learn how iterator works and how you can build your own iterator using __iter__ and __next__ methods. Iterators in Python Iterators are everywhere in Python. They are elegantly implemented within  for  loops, comprehensions, generators etc. but are hidden in plain sight. Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically speaking, a Python  iterator object  must implement two special methods,  __iter__()  and  __next__() , collectively called the  iterator protocol . An object is called  iterable  if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc. are iterables. The  iter()  function (which in turn calls the  __iter__()  method) returns an iterator from them. Iterating Thro...

learnpython24-(Python Generators)

  Python Generators In this tutorial, you'll learn how to create iterations easily using Python generators, how it is different from iterators and normal functions, and why you should use it. Generators in Python There is a lot of work in building an iterator in Python. We have to implement a class with  __iter__()  and  __next__()  method, keep track of internal states, and raise  StopIteration  when there are no values to be returned. This is both lengthy and counterintuitive. Generator comes to the rescue in such situations. Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time). Create Generators in Python It is fairly simple to create a generator in Python. It is as easy as defining a normal function, but with a  yield  ...