Control Structures
The "range" Function
range(start, end, step)
Returns an iterator from [start, end)
, and you can add a step
number like:
range(0, 10, 2)
The current range index will add in steps of 2
.
Don't convert range()
to list(range())
range
map
filter
It is going to occupy A LOT more memory.
"else" in "for" Loops
An else
statement after a for
, is a block of code that will be executed after the loop ends.
If the for loop was stopped with break
, than the else
WILL NOT be executed.
for x in range(6):
...
else:
print("For looop is finished")
Using "pass" Statement
Use pass
to fill empty blocks like if
, for
, class
or etc.
for x in range(6):
pass
Iterator
Are objects which implements the iterator protocol:
__iter__()
__next__()
You can call iter()
function on them and iterate them with next()
.
myIter = iter("banana")
# or
myIter = iter(someList)
...
next(myIter)
next(myIter)
next(myIter)
...
Creating iterators
You can create iterators by implementing the __iter__()
and __next__()
methods.
To avoid an iterator running forever, raise StopIteration
.
class MyIterClass:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a < 20:
self.a += 1
return self.a
else:
raise StopIteration
myIterClass = MyIterClass()
myIter = iter(myIterClass)
next(myIter)
# or
for x in myIterClass:
...
Last updated