I want to master Iterable, Iterator, and Generator, but honestly I can only understand it somehow, so I summarized it briefly so that it is easy to imagine.
An object that can be used repeatedly. Objects of the list, dict, set and str classes are iterable. Simply put, what you can use with *** for syntax ***
Iterators are a type of iterator (iterators are not necessarily iterators) Simply put, it's like a *** list *** returns the current element with next () and advances to the next element Simply put *** Take out something like a list until it's empty ***
If there is a [yield return value] in the function, that function is called a generator function. Also, the list comprehension that is changed from square brackets to parentheses is called a generator expression. Example *** (i for i in range (N)) *** The return value of that function or expression is called a generator iterator. Simply put, it is *** that returns an iterator ***.
Image diagram
Generator features
def sample():
cumsum = 0
for i in range(1, 5):
cumsum += i
print(f'First here →{cumsum}')
yield cumsum
for cumsum in generator_sample2(): #point
print(f'Yield minutes →{cumsum}')
***
Iterator features 1
sample_list = [i for i in range(1, 6)]
print(f'The contents of the list{sample_list}')
sample_iter = iter(sample_list) #iter()Make it an iterator
for i in sample_iter:
print(i)
print(f'The contents of the list do not change{sample_list}')
print(f'Iterator becomes empty when used{list(sample_iter)}')
***
Iterator feature 2
sample_list = [i for i in range(1, 6)]
print(f'The contents of the list{sample_list}')
sample_iter = iter(sample_list) #iter()Make it an iterator
print(f'Something like a list{sample_iter}') #I'm using it here
print(f'Can be seen as a list{list(sample_iter)}')
print(f'Iterator becomes empty when used{list(sample_iter)}')
***
***
** Addition **
@shiracamus Thank you for pointing out.
Recommended Posts