The iter () function in Python

Continuing with the topic of Python's built-in functions, the article will introduce you to the iter () function with the syntax, usage as well as specific examples. Invites you to read the track.

The iter () function is built into Python, returning an iterator of the given object.

The object created from iter () can retrieve each of its elements at a given time, very useful when combined with for, while loops.

Syntax of iter () function in Python:

 iter(object[, sentinel]) 

Read more: Iterator objects in Python

The parameters of iter function ()

The iter () function has 2 parameters:

  1. object : object wants to create iterator, can be set, tuples .
  2. sentinel : special value used to represent the end of the string.

Depending on the parameter passed, iter () will have different properties as follows:

Object parameter
Sentinel parameter
Describe
Object set (set, tuple) No iterator created for object set User defined object (Custom object) None

- execute the __iter __ () and __next __ () methods.
- execute __getitem __ () method with integer arguments starting at 0.

Custom object does not deploy __iter __ (), __next () or __getitem __ () None Exception Exception TypeError exception Callable object Provided Function returns an iterator object that can call an object There is no argument for each call to its __next __ () method, if Sentinel is found, the exception StopIteration exception will be generated.

The value returned from iter ()

The iter () function returns an iterator object for the parameter to be passed , which can iterate through each of its elements at a given time.

In case the second parameter sentinel is passed, the function that returns the iterator object can call the callable object until no sentinel character is found.

Example 1: How does iter () work?

 # danh sach nguyen am # viet boi TipsMake.com nguyenam = ['a', 'e', 'i', 'o', 'u'] nguyenamIter = iter(nguyenam) # in ra 'a' print(next(nguyenamIter)) # in ra 'e' print(next(nguyenamIter)) # in ra 'i' print(next(nguyenamIter)) # in ra 'o' print(next(nguyenamIter)) # in ra 'u' print(next(nguyenamIter)) 

When you run the program, the output output will be:

 aeiou 

Example 2: iter () works with a custom object

 class PrintNumber: def __init__(self, max): self.max = max def __iter__(self): self.num = 0 return self def __next__(self): if(self.num >= self.max): raise StopIteration self.num += 1 return self.num printNum = PrintNumber(3) printNumIter = iter(printNum) # in ra '1' print(next(printNumIter)) # in ra '2' print(next(printNumIter)) # in ra '3' print(next(printNumIter)) # sinh ra StopIteration print(next(printNumIter)) 

Run the program, the result is:

 1 2 3 StopIteration 

Example 3: iter () works with callable object with sentinel

 with open('mydata.txt') as fp: for line in iter(fp.readline, ''): processLine(line) 

When you run the program, Python will open mydata.txt in read mode.

Then iter(fp.readline, '') in the for loop calls readline (read each line in the text file) until the sentinel character '' (empty string) is found.

See also: Built-in Python functions

5 ★ | 1 Vote

May be interested

  • The function set () in PythonThe function set () in Python
    in this article, tipsmake.com will learn with you about set (), syntax, parameters and specific examples. invites you to read the track.
  • Help () function in PythonHelp () function in Python
    the built-in help () function in python is used to display documents and invoke the help system of modules, functions, classes, keywords ...
  • Sum () function in PythonSum () function in Python
    the built-in function sum () in python returns the sum of all numbers in iterable.
  • The slice () function in PythonThe slice () function in Python
    the slice () function in python returns a slice object that helps you determine how to cut an existing string.
  • The chr () function in PythonThe chr () function in Python
    in python, the chr () function returns a character (a string) from an integer that represents the unicode of the returned character.
  • The pow () function in PythonThe pow () function in Python
    the pow () function built into python returns the value of x with the power of y (xy). if there is a third parameter, the function returns x to the power y, the module z.
  • The reversed () function in PythonThe reversed () function in Python
    the reversed () function is one of the built-in functions in python, used to reverse the original string returning the iterator.
  • Exec () function in PythonExec () function in Python
    the exec () function used to execute python programs dynamically can be string or object code. how does exec () function syntax, what parameters do it have, and how is it used? invites you to read the track.
  • Built-in Python functionsBuilt-in Python functions
    in the previous article, you learned that python has a basic function type, one is a built-in function, two are user-defined functions. today, we will learn about a list of python's built-in functions.
  • The compile () function in PythonThe compile () function in Python
    the compile () function returns a code object in python from the specified source. so how to use compile () function? please find out in this article.