Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python iter() Function



ThePython iter() function is abuilt-in function that is used to obtain an iterator from an iterable object. An iterable is an object that enables us to access one item at a time by iterating over them, such aslists,tuples,strings, etc.

Syntax

Following is the syntax of the Pythoniter() function −

iter(object, sentinel)

Parameters

The Pythoniter() function accepts two parameters −

  • object − It represents an object such as a list, string, or tuple.

  • sentinel − It is an optional parameter. When the sentinel value is provided, iteration will continue until the value returned by the iterator matches the sentinel.

Return Value

The Pythoniter() function returns an iterator object.

iter() Function Examples

Practice the following examples to understand the use ofiter() function in Python:

Example: List to Iterator Using iter() Function

In the code below, we are converting a given list into an iterator object by using the iter() function and then, printing the first two elements with the help of next() function.

numericLst = [55, 44, 33, 22, 11]iteration = iter(numericLst)print("The first two items from the iterator is:")print(next(iteration)) print(next(iteration))

Following is an output of the above code −

The first two items from the iterator is:5544

Example: iter() Function With for Loop

The code below demonstrates how to use iter() function with thefor loop. Here, we are displaying the elements of the specified list after converting it to iterator object.

numericLst = [55, 44, 33, 22, 11]iteration = iter(numericLst)print("All items from the iterator are:")for item in iteration:   print(item)

Output of the above code is as follows −

All items from the iterator are:5544332211

Example: Tuple to Iterator Using iter() Function

In the code below a tuple is created and then converted into an iterator object using iter() method. Furthermore, we display the first two elements of this object with the help of "for" and "if" loops.

fruitTuple = ("Grapes", "Orange", "Banana", "Apple")iterator = iter(fruitTuple)print("The first two items from the iterator are:")counter = 0for item in iterator:   if counter < 2:      print(item)      counter += 1   else:      break

Following is the output of the above Python code −

The first two items from the iterator are:GrapesOrange

Example: iter() Function With String

The iter() method can also be used with the string to display its characters one at a time as illustrated in the below example.

orgName = "TutorialsPoint"iterator = iter(orgName)print("The characters of the given string are:")for item in iterator:   print(item)

The above program, on executing, displays the following output −

The characters of the given string are:TutorialsPoint
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp