Follow me
What is an Iterable in Python?
An iterable is an object that contains a collection of items and allows you to go through those items one by one. It’s like a box of things, and you can use a for loop to take out each item one at a time.
How to Identify an Iterable?
Some common iterables in Python are:
List: [1, 2, 3]
String: "hello"
Tuple: (4, 5, 6)
Dictionary: {'a': 1, 'b': 2}
Set: {7, 8, 9}
These are all iterable because you can loop over them with a for loop.
How to Create an Iterable?
You can create an iterable by making a class that defines the __iter__() method. This method tells Python how to start the iteration. You’ll also need the __next__() method to return the next item in the sequence.
Simple Example of a Custom Iterable:
class MyNumbers:
def __iter__(self):
self.num = 1 # Start from 1
return self
def __next__(self):
if self.num <= 5: # Limit the sequence to 5
result = self.num
self.num += 1
return result
else:
raise StopIteration # Stop when the sequence ends
# Create an iterable object
my_iterable = MyNumbers()
# Use a for loop to iterate over it
for number in my_iterable:
print(number)
Output:
1
2
3
4
5
Explanation:
1. __iter__(): Prepares the object for iteration (like setting the starting point).
2. __next__(): Returns the next item and stops when done.
3. for loop: Goes through the items one by one.
Iterable vs Iterator in Python
Though related, iterable and iterator are different concepts.
1. What is an Iterable?
An iterable is an object that contains a collection of items and can be looped over using a for loop.
Examples: Lists, Strings, Tuples, Dictionaries, Sets.
It doesn’t produce items directly—it only provides a way to get an iterator to do the work.
2. What is an Iterator?
An iterator is an object that remembers where it is in the sequence and returns one item at a time when asked using the next() function.
Iterators are produced from iterables by calling the iter() function.
Iterators stop when there are no more items left, raising StopIteration.
Iterable vs Iterator
# A list is an iterable
my_list = [1, 2, 3]
# Converting the list to an iterator
my_iterator = iter(my_list)
# Using next() to get items from the iterator
print(next(my_iterator)) # Output: 1
print(next(my_iterator)) # Output: 2
print(next(my_iterator)) # Output: 3
# If we try next() again, it will raise StopIteration
Explanation:
1. Iterable (my_list):
A list is an iterable.
You can use a for loop or convert it into an iterator.
2. Iterator (my_iterator):
The iter() function converts the list into an iterator.
The next() function gives the next item from the iterator.
When there are no more items, it raises a StopIteration error.
Key Differences:
Summary:
Iterable: A collection you can loop through, like a list or string.
Iterator: An object that gives one item at a time from the iterable when you call next().
This distinction helps Python manage data efficiently, especially with large collections.
No comments:
Post a Comment