Python is a versatile programming language that offers many built-in functions to help developers perform various tasks. One of the most useful built-in functions is "iter()", which creates an iterator object that can be used to traverse a sequence.
The "iter()" function is often used in combination with the "next()" function to create a loop that iterates over a sequence until the end is reached. The "next()" function retrieves the next item in the sequence, and the "iter()" function creates the iterator object.
Syntax: The syntax for the "iter()" function is as follows:
|
iter(object[, sentinel])
|
where:
Example 1:
|
my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
|
In this example, we have created a list "my_list" and an iterator "my_iterator" using the "iter()" function. We then use the "next()" function to iterate over the list and print out each item in the sequence. The output of this code will be:
Output:
|
1
2
3
4
5
|
Example 2:
|
my_tuple = (1, 2, 3, 4, 5)
my_iterator = iter(my_tuple)
for i in range(len(my_tuple)):
print(next(my_iterator))
|
In this example, we have created a tuple "my_tuple" and an iterator "my_iterator" using the "iter()" function. We then use a for loop to iterate over the length of the tuple and print out each item in the sequence using the "next()" function. The output of this code will be the same as the previous example:
Output:
|
1
2
3
4
5
|
Example 3:
|
my_string = "Hello World"
my_iterator = iter(my_string)
while True:
try:
print(next(my_iterator))
except StopIteration:
break
|
In this example, we have created a string "my_string" and an iterator "my_iterator" using the "iter()" function. We then use a while loop to iterate over the string and print out each character in the sequence using the "next()" function. We also use a try-except block to catch the "StopIteration" exception, which is raised when the end of the sequence is reached. The output of this code will be:
Output:
|
H
e
l
l
o
W
o
r
l
d
|
In conclusion, the "iter()" function is a powerful built-in function in Python that allows developers to create an iterator object for any sequence. It is often used in combination with the "next()" function to create a loop that iterates over the sequence until the end is reached.