-
Notifications
You must be signed in to change notification settings - Fork 87
1. Iterables, Sequences, and Iterators
Iterable is an object that can be looped over. It represents a collection of elements that can be accessed one by one.
We can use the following function to test if an object is an iterable:
def is_iterable(param):
try:
iter(param)
return True
except TypeError:
return FalseLet's save some objects in a dictionary and test them:
python_objects = {
"Integer": 1,
"Float": 1.2,
"Boolean": True,
"Complex": 1 + 2j,
"String": "Hello",
"List": [1, 2, 3],
"Tuple": (1, 2, 3),
"Set": {1, 2, 3},
"Dictionary": {"a": 1, "b": 2, "c": 3},
"None": None,
"Range": range(10),
"Generator": (i for i in range(10)),
"Function": is_iterable,
"Lambda": lambda x: x**2,
}
for name, obj in python_objects.items():
print(f"{name:12}: {is_iterable(obj)}")We get the following output and detect the iterable object:
Integer : False
Float : False
Boolean : False
Complex : False
String : True
List : True
Tuple : True
Set : True
Dictionary : True
None : False
Range : True
Generator : True
Function : False
Lambda : False
Sequence is a subtype of iterables. It is an ordered collection of elements that can be indexed by numbers.
Let's take a look at to the most common iterables and check them if they are a sequence or not:
python_iterables = {
"String": "Hello",
"List": [1, 2, 3],
"Tuple": (1, 2, 3),
"Set": {1, 2, 3},
"Dictionary": {"a": 1, "b": 2, "c": 3},
}
def is_sequence(param):
try:
param[0]
return True
except:
return FalseWe get the following output:
String : True
List : True
Tuple : True
Set : False
Dictionary : False
Iterator is an object that produces items from its associated iterable. Iterator protocol consists of two methods namely, __iter__ and __next__.
class AnIteratorClass:
def __init__(self):
self.a = 1
def __iter__(self):
return self
def __next__(self):
if self.a <= 5:
x = self.a
self.a += 1
return x
else:
raise StopIterationNow we can use the following test:
def is_iterator(param):
try:
next(param)
return True
except TypeError:
return FalseAlso a very simple way to create iterators is to use generators:
def generator_function():
for i in range(10):
yield iAs a conclusion we can summarize the status of the Python objects that we will use in this course as given below:
| Name | Iterable | Iterator | Sequence |
|---|---|---|---|
| Integer | False | False | False |
| Float | False | False | False |
| Boolean | False | False | False |
| Complex | False | False | False |
| String | True | False | True |
| List | True | False | True |
| Tuple | True | False | True |
| Set | True | False | False |
| Dictionary | True | False | False |
| None | False | False | False |
| Range | True | False | True |
| Generator | True | True | False |
| Function | False | False | False |
| Lambda | False | False | False |