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 Programming Course & Exercises
Example
Create iterable
Define a dictionary and an iterable like the code below:
1 | #!/usr/bin/python |
You can loop over the items like so:
1 | for item in iterable: |
Next method
Create an iterator to use the next method:
1 | #!/usr/bin/python |
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:
1 | items = [ "one","two","three","four" ] |
If you are a beginner, then I highly recommend this book.
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: