The iter() function in Python is a built-in function used to convert an iterable object into an iterator. An iterator is an object that allows elements to be accessed one at a time, making it useful for sequential processing of data.
Common iterable objects include lists, tuples, strings, sets, and dictionaries. The iter() function enables us to traverse these objects step by step using the next() function.
iter(object, sentinel)
object An iterable object (such as a list, tuple, or string).
sentinel (optional) A value that signals the end of iteration when using a callable.
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Output
10
20
30
Explanation
iter(numbers) converts the list into an iterator.next(it) retrieves elements one by one.text = "Python"
it = iter(text)
print(next(it))
print(next(it))
Output
P
y
Explanation
next() returns the next character.iter() in a Loopnumbers = [1, 2, 3]
it = iter(numbers)
for item in it:
print(item)
Output
1
2
3
Explanation
numbers = [1, 2]
it = iter(numbers)
while True:
try:
print(next(it))
except StopIteration:
break
Output
1
2
Explanation
iter() with Sentinel Valueimport random
def get_number():
return random.randint(1, 5)
for num in iter(get_number, 3):
print(num)
Explanation
| Term | Description |
|---|---|
| Iterable | Object that can be converted into an iterator (list, tuple, string) |
| Iterator | Object that produces elements one at a time using next() |
Example:
numbers = [1, 2, 3]
it = iter(numbers)
numbers → iterableit → iteratoriter() is a built-in Python function used to create an iterator from an iterable object.next() function.