An iteratable is a Python object that can be used as a sequence. You can go to the next item of the sequence using the next() method.

You can loop over an iterable, but you cannot access individual elements directly.
It’s a container object: it can only return one of its element at the time.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Create iterable

Define a dictionary and an iterable like the code below:

#!/usr/bin/python
d = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 }
iterable = d.keys()
print(iterable)

You can loop over the items like so:

for item in iterable:
print(item)

Next method

Create an iterator to use the next method:

#!/usr/bin/python
d = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5 }
iterable = d.keys()
iterator = iter(iterable)
print( next(iterator) )
print( next(iterator) )

Iterable types

You cannot access elements using an index, this will raise an exception.
Iterable object types includes lists, strings, dictionaries and sets.

The demo below applies an iterator to a list:

items = [ "one","two","three","four" ]
iterator = iter(items)
x = next(iterator)
print(x)

Exercise

Try the exercises below

  • What is an iterable?
  • Which types of data can be used with an iterable?

You can download the answers below:

Download answers