3-1-4-14. [Optional] Iterators and Generators

It turns out many of the built-in functions we’ve used so far,

such as enumerate, returns something called an iterator.

An iterator is an object that represents a stream of data.

This is different from a list which is also an iterable

but not an iterator since it is not a stream of data.

Soon, you’ll see some reasons that iterators are favored in different situations.

Here we will learn how to create iterators using generators.

Generators are a simple way to create iterators using functions.

However, it’s not the only way to create iterators.

You can read more about this in the notes below.

These terms may be a little confusing.

The term generator is often used to refer to the generator function,

but it’s also used to refer to the iterator object produced by the function.

Here I’ll differentiate these by referring to the function as a generator function,

and what it produces as the iterator.

Here is a generator function called ‘my range’ that

produces a stream of numbers from zero to x minus one.

Notice that instead of using the return keyword, this uses yield.

This allows the function to return values one at a time

and start where it left off each time it’s called.

This yield keyword is what differentiates a generator from a typical function.

As you can see here,

calling my range four returns an iterator that we can then iterate through.

Using a for loop,

we can print values from this stream of data.

Here this prints zero, one, two and three.

In the next section,

you’ll get some practice writing generator functions to create your own iterators

이전 수업을 기억한다면,

iterables는 한 번에 요소 중 하나를 반환할 수 있는 객체입니다.

목록은 당신이 사용한 가장 일반적인 이터러블 중 하나입니다.

우리가 지금까지 사용했던 많은 내장 함수들이 밝혀졌습니다.

enumerate와 같이 iterator라는 것을 반환합니다.

반복자는 데이터 스트림을 나타내는 개체입니다.

이것은 반복 가능한 목록과 다릅니다.

그러나 데이터 스트림이 아니기 때문에 반복자는 아닙니다.

곧, 다양한 상황에서 반복자가 선호되는 몇 가지 이유를 알게 될 것입니다.

여기서는 제너레이터를 사용하여 반복자를 만드는 방법을 배웁니다.

제너레이터는 함수를 사용하여 반복자를 만드는 간단한 방법입니다.

그러나 반복자를 만드는 유일한 방법은 아닙니다.

이에 대한 자세한 내용은 아래 메모에서 확인할 수 있습니다.

이 용어는 약간 혼란스러울 수 있습니다.

제너레이터라는 용어는 종종 제너레이터 기능을 나타내는 데 사용됩니다.

그러나 함수에 의해 생성된 반복자 객체를 참조하는 데에도 사용됩니다.

여기에서 함수를 생성기 함수로 참조하여 이들을 구별하겠습니다.

반복자로 생성하는 것입니다.

다음은 ‘my range’라는 생성기 함수입니다.

0에서 x 빼기 1까지의 숫자 스트림을 생성합니다.

return 키워드를 사용하는 대신 yield를 사용합니다.

이렇게 하면 함수가 한 번에 하나씩 값을 반환할 수 있습니다.

호출될 때마다 중단된 위치에서 시작합니다.

이 yield 키워드는 생성기를 일반적인 함수와 구별하는 것입니다.

여기에서 볼 수 있듯이,

내 범위를 네 번 호출하면 반복할 수 있는 반복자가 반환됩니다.

for 루프를 사용하여,

이 데이터 스트림에서 값을 인쇄할 수 있습니다.

여기서 이것은 0, 1, 2, 3을 인쇄합니다.

다음 섹션에서는

자신만의 반복자를 만들기 위해 생성기 함수를 작성하는 연습을 하게 될 것입니다.

Iterators And Generators

Iterables are objects that can return one of their elements at a time, such as a list. Many of the built-in functions we’ve used so far, like ‘enumerate,’ return an iterator.

An iterator is an object that represents a stream of data. This is different from a list, which is also an iterable, but is not an iterator because it is not a stream of data.

Generators are a simple way to create iterators using functions. You can also define iterators using classes, which you can read more about here.

Here is an example of a generator function called my_range, which produces an iterator that is a stream of numbers from 0 to (x – 1).

def my_range(x):
    i = 0
    while i < x:
        yield i
        i += 1

Notice that instead of using the return keyword, it uses yield. This allows the function to return values one at a time, and start where it left off each time it’s called. This yield keyword is what differentiates a generator from a typical function.

Remember, since this returns an iterator, we can convert it to a list or iterate through it in a loop to view its contents. For example, this code:

for x in my_range(5):
    print(x)

outputs:

0
1
2
3
4

Why Generators?

You may be wondering why we’d use generators over lists. Here’s an excerpt from a stack overflow page that addresses this:

Generators are a lazy way to build iterables. They are useful when the fully realized list would not fit in memory, or when the cost to calculate each list element is high and you want to do it as late as possible. But they can only be iterated over once.

https://softwareengineering.stackexchange.com/questions/290231/when-should-i-use-a-generator-and-when-a-list-in-python/290235

%d