Objects-iterators. Using iterators and generators for lists. Functions range(), next(), iter()
Contents
- 1. What are objects-iterators (iterable objects)?
- 2. What is the iterations protocol?
- 3. What are the iterators of lists?
- 4. Using functions next() and iter() to traverse the list. Examples
- 5. Using the __next __() function to bypass the list. Example
- 6. Manual and automatic ways to perform iterations. Example
- 7. What are list generators?
- 8. An example of generating a list based on an existing list
- 9. Function range().Generating a list. Examples
- Related topics
Search other websites:
1. What are objects-iterators (iterable objects)?
An iterator object is an object that meets the following criteria:
- an object is a sequence that can be physical or virtual. A virtual sequence is formed on demand;
- in conjunction with the for loop, the object returns one result (element) from the sequence. Such objects include lists, tuples, strings.
⇑
2. What is the iterations protocol?
The iteration protocol is the behavior of the object being iterated, in which:
- the object being iterated implements the __next __() method to get the next value in the sequence;
- after receiving a series of results and for its termination, the object being iterated generates an exception StopIteration.
⇑
3. What are the iterators of lists?
Iterators of lists are objects:
- that support the ability to iterate through sequences;
- which are returned by the iter() function and also support the next() function. The operation of these functions is described below.
Iterators of lists are applied to iterable objects (objects-iterators). Iterable objects can be lists, tuples, strings.
⇑
4. Using functions next() and iter() to traverse the list. Examples
The next() and iter() functions are intended for manually traversing lists. The next() function is used to get the next element in the sequence (in the object to be iterated). The function next() refers to the function __next __() (see item 5).
The iter() function is used to get an iterator object. Each iteratable object has a built-in __next __() method.
Example 1. Traversing the list using the iter() and next() functions.
# traversing the list using the iter() and next() functions # specified list A = [ 3, 8, 12, 20 ] # get an iteratable object for list A I = iter(A) print("I = ", I) # get the current value and go to the next element of the sequence t = next(I) # t = 3 print("t = ", t) # next list item t = next(I) # t = 8 print("t = ", t)
The result of the program
I = <list_iterator object at 0x03DD1870> t = 3 t = 8
Example 2. Reading a text file
A text file is specified in which numbers (or other information) are recorded. The file is located on the disk in the following path
E:\1\myfile.txt
Below is the program code for reading information from a file using the iter() and next() functions.
# reading from file using iter () and next () functions # given file e:\1\myfile.txt fp = open('e:\\1\\myfile.txt') # read file using while loop I = iter(fp) # get iterator # the loop of displaying lines in a file while True: try: t = next(I) # the attempt to take the next line in the file except: StopIteration # stop iterations if end of file break print(t, end='') # print a string
The result of the program will output the contents of the file. For the correct completion of reading the file, use the try…except block.
In the print() function, if you remove the line
end=''
then each line in the output file will be added extra new line.
⇑
5. Using the __next __() function to bypass the list. Example
The __next __() function is used to bypass the list in the same way as the next() function. The __next __() function is used for the object being iterated.
The example demonstrates bypass of the list using the __next __() function. To create an iterator object, the iter() function is called.
# bypassing the list using the iter() and next() functions # specified list A = [ 'abc', 'AAA', 'BBB' ] # get an iterator object for list A IA = iter(A) print("IA = ", IA) # display the current value and go to the next item in the list t = IA.__next__() # t = 'abc' print("t = ", t) # next list item t = IA.__next__() print("t = ", t) # t = 'AAA' # next item t = IA.__next__() print("t = ", t) # t = 'BBB' # attempt to take the next item that is not on the list t = IA.__next__() # exception StopIteration print("t = ", t)
As a result of the program, the following result will be obtained.
IA = <list_iterator object at 0x040D7850> t = abc t = AAA t = BBB Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\Lists04.py", line 23, in <module> t = IA.__next__() StopIteration
As can be seen from the result, an attempt to cause a non-existent list item will cause a StopIteration exception.
⇑
6. Manual and automatic ways to perform iterations. Example
Iterations in the sequence can be performed manually or automatically. The automatic method involves the use of a for loop. For the organization of a manual way to perform iterations, a while loop is used.
In the automatic method of obtaining an iterator with the iter() function, the iterator increment with the next() function and the StopIteration exception processing are performed automatically.
In the manual method in the while loop, the sequence is processed using the try…except block. This block performs an operation and catches exceptions that may occur. An example of the organization of automatic and manual ways to perform iterations for a list
# manual and automatic ways to perform iterations # specified list A = [ 2, 3, 5, 7, 15 ] # automatic way to iterate print("Automatic way:") for t in A: print(t*t) # manual way print("\nManual way:") I = iter(A) # get iterator for list A while True: try: t = next(I) # same as I.__next__() except StopIteration: break print(t**3)
The result of the program:
Automatic way: 4 9 25 49 225 Manual way: 8 27 125 343 3375
⇑
7. What are list generators?
List generators are tools that allow you to form lists based on a given expression or rule using an iteration protocol.
With the help of generators, lists can be obtained:
- based on previously created lists;
- using built-in python tools, such as the range() function.
⇑
8. An example of generating a list based on an existing list
In the example, based on the existing list A, another list B is formed. Each item of list B is multiplied by the value 2.2.
# list generator # create a list of pair numbers from 0 to 10 A = [ 2, 4, 6, 8, 10 ] # based on the data in list A create another list B = [ t*2.2 for t in A ] print("A = ", A) print("B = ", B)
In the above example, in the line
B = [ t*2.2 for t in A ]
sequentially stretched element by element from the list A. The resulting element is written to the object t. Before the for keyword is indicated the formula to create a new list
t*2.2
According to this example, you can create your own new lists based on other previously created lists.
The result of the program
A = [2, 4, 6, 8, 10] B = [4.4, 8.8, 13.200000000000001, 17.6, 22.0]
⇑
9. Function range().Generating a list. Examples
To generate lists, the built-in functions of Python are used. A common function for generating sequences is the range() function.
The range() function can take from 1 to 3 parameters. Depending on the number of parameters, the function forms a range of integers according to the appropriate rules. The following are features of the range() function depending on the number of parameters received:
- 1 parameter – this parameter indicates the value of the maximum element in the sequence (upper limit). The minimum element in the sequence is 0. If you specify a negative value as a parameter, then the function returns an empty sequence. The step between adjacent elements of the sequence is 1;
- 2 parameters. The first parameter indicates the smallest element in the sequence. The second parameter indicates the largest element in the sequence. The step between adjacent elements of the sequence is 1;
- 3 parameters. The first two parameters indicate the smallest and largest elements of the sequence, respectively. The third parameter specifies the step change when forming the next element of the sequence.
Example 1. Generating a list of integers using function range().
# list generators # 1. Generate a list of numbers, increment step = 1 A = list(range(-5,5)) # A = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] # 2. Generate a list of 5 numbers on the interval [0,10] with step 2 B = list(range(0,10,2)) # B = [0, 2, 4, 6, 8] print("A = ", A) print("B = ", B)
The result of the program
A = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] B = [0, 2, 4, 6, 8]
Example 2. Change the list using the range() function.
# Change the list using the range () function. # create a list A = list(range(10,50,5)) print("A = ", A) # edit list - double every list item for i in range(len(A)): A[i]*=2 print("A*2 = ", A)
The result of the program
A = [10, 15, 20, 25, 30, 35, 40, 45] A*2 = [20, 30, 40, 50, 60, 70, 80, 90]
Example 3. Use the range() function, which takes one parameter.
# range() function with a single parameter # create a list of numbers from 1 to 10 A = list(range(10)) # A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print("A = ", A)
The result of the program
A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
⇑
Related topics
- Lists. List properties. Examples that demonstrate properties of lists
- Operation with lists: concatenation (+), duplication (–), deletion, slice, access by index
- Lists processing in loops. Generating lists using lists generators. Iterations through the lists. Presentation and processing matrices using lists. Operation in
- Methods for working with lists. Examples
⇑