Skip to content

1. Iterables, Sequences, and Iterators

Bora Canbula edited this page Nov 25, 2023 · 1 revision

Iterables

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 False

Let'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

Sequences

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 False

We get the following output:

String      : True
List        : True
Tuple       : True
Set         : False
Dictionary  : False

Iterators

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 StopIteration

Now we can use the following test:

def is_iterator(param):
    try:
        next(param)
        return True
    except TypeError:
        return False

Also a very simple way to create iterators is to use generators:

def generator_function():
    for i in range(10):
        yield i

Result

As 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
Clone this wiki locally