lettura facile

Iterable Objects in Python

This tutorial delves into the fascinating realm of iterable objects within Python.

So, what exactly is an iterable? In essence, an iterable is a container object that allows one to access its elements either via an index or through a method that can return an "iterator" using a for loop. This category of objects includes lists, tuples, strings, dictionaries, sets, generators, and more.

What makes an iterable object unique are certain special methods:

  • The __iter__() method
    This is the method that returns an iterator.

    object.__iter__()

  • The __next__() method
    This method returns the next element within the container, relative to the current position. If all elements have been returned, it raises a "StopIteration" exception, which halts iterations and concludes the reading cycle.

    object.__next__()

Why are iterable objects useful?

They shine particularly when you need to perform an operation on each element within a data collection.

For instance, you could use an iterable to check if a certain word appears in a text, or to calculate the mean or sum of values within a data sequence.

Python's iterable objects also serve as the backbone for generators and comprehensions, two indispensable tools for creating compact, readable, and efficient code.

A Practical Illustration

To better grasp these concepts, let's dive into a practical example.

Let's start by creating a string object.

>>> myString = "Python"

Next, let's check if the string has the `__iter__()` method which can turn it into an iterable.

This can be verified using the `hasattr()` function.

>>> hasattr(myString, '__iter__')
True

As the output is "True," the string can indeed be transformed into an iterator.

Now, let's use the `__iter__()` method to transform the string into an iterator:

>>> obj=myString.__iter__()

Or alternatively, we can achieve the same result using the `iter()` function instead of the `__iter__()` method:

>>> obj=iter(stringa)

Next, let's see if the "obj" iterable that we just created is also an iterator, i.e., if it has the `__next__()` method:

>>> hasattr(obj, '__next__')
True

The output is True. Hence, "obj" is indeed an iterator.

At this point, we can use the `__next__()` method to read every single element of the string, one after another.

On the first call, the `next` method returns the first character "P":

>>> obj.__next__()
P

You can achieve the same result using the `next()` function instead of the `__next__()` method:

>>> next(obj)

On the second call, it returns the second character of the string, namely "y":

>>> obj.__next__()
y

On the third call, it returns the third character of the string, which is "t":

>>> obj.__next__()
t

And so forth, until the last character of the string.

Understanding the Difference Between Iterables and Iterators

Depending on whether an object possesses one or both methods, it can be classified as either an iterable or an iterator:

  • An iterable object has the `iter()` method.
  • An iterator object has both the `iter()` and `next()` methods.

Therefore, an iterator is always an iterable, but the converse is not necessarily true.

For example, a set object is "iterable" as it has the `iter()` method, but it's not an "iterator" because it lacks the `next()` method. Let's put this to the test with a practical example by creating a set object:

>>> s = {1,2,3}

Now, let's verify if it has the "iter" method using the `hasattr()` function:

The output is "True", so the set is indeed an iterable.

>>> hasattr(s,'__iter__')
True

Next, let's check if it also has the "next" method.

The output is "False," which means the set is not an iterator.

>>> hasattr(s,'__next__')
False

Still, you can transform the set into an iterator using the `__iter__()` method.

>>> obj = s.__iter__()

After the transformation, the "obj" object is an iterator because it has both the "iter" attribute:

>>> hasattr(obj,'__iter__')
True

and the "next" attribute:

>>> hasattr(obj,'__next__')
True

Keep in mind that it's possible to create multiple independent iterators from a single iterable object.

For instance, let's create two iterator objects from the same list

>>> s = [1,2,3]
>>> obj1 = s.__iter__()
>>> obj2= s.__iter__()

You can now iterate over each of these iterators (obj1 and obj2) independently. This is because they are distinct objects, despite originating from the same iterable.

>>> obj1 is obj2

False

Examples of Iterable Objects

Let's now delve into some practical examples of iterable objects in Python

1] Lists

A list is a data structure that contains a sequence of data of the same type or of different types.

  1. myList = [1, 2, 3, 4, 5]
  2. for i in myList:
  3. print(i)

The for loop returns the elements of the list one after another.

1
2
3
4
5

2] Tuples

A tuple is similar to a list, but it's immutable. Once defined, you cannot modify it during the execution of the program or the working session.

  1. myTuple = (1, 2, 3, 4, 5)
  2. for i in myTuple:
  3. print(i)

Similarly, the for loop here returns all elements of the tuple, one at a time.

1
2
3
4
5

3] Strings

Strings are yet another iterable object in Python.

  1. myString = "Python"
  2. for char in myString:
  3. print(char)

Each iteration here accesses each character of the string.

P
y
t
h
o
n

4] Dictionaries

A dictionary is a data structure that stores data in the form of key-value pairs. When iterating over a dictionary, you're accessing the keys by default..

  1. myDict = {'one': 1, 'two': 2, 'three': 3}
  2. for key in myDict:
  3. print(key)

This loop prints all the keys present in the dictionary.

one
two
three

However, you can access the values or key-value pairs using the appropriate methods.

For instance, you can access the values using the `values()` method:

  1. myDict = {'one': 1, 'two': 2, 'three': 3}
  2. for value in myDict.values():
  3. print(value)

This loop prints all the values of the dictionary.

1
2
3

To access key-value pairs, you can use the `items()` method:

  1. myDict = {'one': 1, 'two': 2, 'three': 3}
  2. for key, value in myDict.items():
  3. print(key, value)

This loop prints all keys and values of the dictionary.

one 1
two 2
three 3

4] File

Files are another example of an iterable object. Once opened, you can iterate through the file to read each line of text (record).

  1. with open("file.txt", "r") as file:
  2. for line in file:
  3. print(line)

In each iteration, Python reads a line from the file, one after another, until it reaches the end of the file (EOF).




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin