Skip to content

Instantly share code, notes, and snippets.

@Robofied
Created February 10, 2019 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Robofied/8bdcc93f05ec9588f13fb2d3debe3f63 to your computer and use it in GitHub Desktop.
Save Robofied/8bdcc93f05ec9588f13fb2d3debe3f63 to your computer and use it in GitHub Desktop.
Intermediate Python
## Creating a range object
x = range(4)
## Printing that object
x
#[Output]:
#range(0, 4)
#Here, there is no next method associated with the range object.
#But if we will create a generator using range object then next()function will work because the generator has special method next.
next(x)
#[Output]:
#---------------------------------------------------------------------------
#StopIteration Traceback (most recent call last)
#<ipython-input-13-92de4e9f6b1e> in <module>()
#----> 1next(x)
#StopIteration:
#Checking the magical/special methods using dir() function of range class.
print(dir(range))
#[Output]:
#['__bool__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
## Creating a generator and checking the special methods
## Creating a generator
x = (i for i in range(5))
## Printing and it will not print value, it will print generator object
x
#[Output]:
#<generator object <genexpr> at 0x000001F0D9436048>
## Here next will work even generator is created using range because generator has __next__ method with it.
## Using the next method of generator class, can access the next value.
next(x)
#[Output]:
#0
## Printing the other value using for loop
for i in x:
print(i)
#[Output]:
#1
#2
#3
#4
## Checking the special methods of generator function.
print(dir(x))
#[Output]:
#['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment