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
2
3
4
#!/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:
1
2
for item in iterable:
print(item)
Next method
Create an iterator to use the next method:
1
2
3
4
5
6
#!/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:
1
2
3
4
items = [ "one","two","three","four" ]
iterator = iter(items)
x = next(iterator)
print(x)
If you are a beginner, then I highly recommend this YouTube Python Playlist.
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: