Python 이터레이터에서 next() 로 다음 요소 가져오는 방법

PythonBeginner
지금 연습하기

소개

이 튜토리얼에서는 Python 이터레이터 (iterator) 에서 next() 함수를 사용하여 요소에 접근하는 방법을 배우게 됩니다. 이터레이터는 Python 에서 데이터를 한 번에 하나씩 처리할 수 있게 해주는 기본적인 객체입니다. next() 함수를 마스터하면 더 효율적인 코드를 작성하고 데이터 처리를 더 잘 제어할 수 있습니다.

이 튜토리얼을 통해 이터레이터를 생성하고 조작하며, 이터레이터 예외를 처리하고, 실제 프로그래밍 시나리오에서 이터레이터의 실용적인 응용을 탐구할 것입니다.

기본 이터레이터 생성 및 사용

Python 에서 이터레이터는 한 번에 하나씩 요소의 컬렉션을 순회할 수 있게 해주는 객체입니다. 기본적인 이터레이터를 생성하고 사용하는 방법을 먼저 살펴보겠습니다.

리스트에서 이터레이터 생성하기

먼저, VSCode 편집기를 열고 새 Python 파일을 생성해 보겠습니다.

  1. 탐색기 패널 (왼쪽) 에서 프로젝트 폴더를 클릭합니다.
  2. 마우스 오른쪽 버튼을 클릭하고 "New File"을 선택합니다.
  3. 파일 이름을 basic_iterator.py로 지정합니다.

이제 basic_iterator.py에 다음 코드를 추가합니다.

## Create a simple list
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

## Convert the list to an iterator
fruits_iterator = iter(fruits)

## Print the type of the iterator
print("Type of fruits_iterator:", type(fruits_iterator))

## Use next() to get the first element
first_fruit = next(fruits_iterator)
print("First fruit:", first_fruit)

## Get the second element
second_fruit = next(fruits_iterator)
print("Second fruit:", second_fruit)

## Get the third element
third_fruit = next(fruits_iterator)
print("Third fruit:", third_fruit)

코드 실행하기

코드를 실행하려면 WebIDE 에서 터미널을 엽니다.

  1. 상단 메뉴에서 "Terminal"을 클릭합니다.
  2. "New Terminal"을 선택합니다.
  3. 터미널에서 다음을 실행합니다.
python3 ~/project/basic_iterator.py

다음과 유사한 출력을 볼 수 있습니다.

Type of fruits_iterator: <class 'list_iterator'>
First fruit: apple
Second fruit: banana
Third fruit: cherry

무슨 일이 일어났는지 이해하기

무슨 일이 일어났는지 자세히 살펴보겠습니다.

  1. fruits라는 다섯 개의 요소가 있는 리스트를 생성했습니다.
  2. iter() 함수를 사용하여 리스트를 이터레이터로 변환했습니다.
  3. 이터레이터의 유형을 출력하여 list_iterator 객체임을 보여주었습니다.
  4. next() 함수를 세 번 사용하여 이터레이터에서 처음 세 개의 요소를 가져왔습니다.

next()를 호출할 때마다 이터레이터는 컬렉션의 다음 요소로 이동하여 반환합니다. 이터레이터는 자신의 위치를 추적하므로 호출 사이에서 어디에서 멈췄는지 기억합니다.

직접 해보기

이제 코드를 수정하여 이터레이터에서 나머지 요소를 가져오십시오. 파일 끝에 다음 줄을 추가합니다.

## Get the fourth element
fourth_fruit = next(fruits_iterator)
print("Fourth fruit:", fourth_fruit)

## Get the fifth element
fifth_fruit = next(fruits_iterator)
print("Fifth fruit:", fifth_fruit)

파일을 저장하고 다시 실행합니다.

python3 ~/project/basic_iterator.py

이제 다섯 개의 모든 과일이 콘솔에 출력되는 것을 볼 수 있습니다.

핵심 개념

  • **Iterable (반복 가능한 객체)**은 리스트, 튜플, 문자열과 같이 반복할 수 있는 모든 객체입니다.
  • **Iterator (이터레이터)**는 __iter__()__next__() 메서드를 사용하여 이터레이터 프로토콜을 구현하는 객체입니다.
  • iter() 함수는 반복 가능한 객체를 이터레이터로 변환합니다.
  • next() 함수는 이터레이터에서 다음 요소를 가져옵니다.

StopIteration 처리 및 기본값 사용

Python 에서 이터레이터를 사용할 때 이터레이터의 끝에 도달했을 때 어떤 일이 발생하는지 알아야 합니다. 이 상황을 처리하는 방법을 살펴보겠습니다.

이터레이터의 끝에서 무슨 일이 발생하는가?

프로젝트 폴더에 stop_iteration.py라는 새 파일을 생성합니다.

  1. 탐색기 패널에서 프로젝트 폴더를 마우스 오른쪽 버튼으로 클릭합니다.
  2. "New File"을 선택합니다.
  3. 파일 이름을 stop_iteration.py로 지정합니다.

다음 코드를 추가합니다.

## Create a small list
numbers = [1, 2, 3]

## Convert the list to an iterator
numbers_iterator = iter(numbers)

## Retrieve all elements and one more
print(next(numbers_iterator))  ## 1
print(next(numbers_iterator))  ## 2
print(next(numbers_iterator))  ## 3
print(next(numbers_iterator))  ## What happens here?

터미널에서 코드를 실행합니다.

python3 ~/project/stop_iteration.py

다음과 같은 오류 메시지가 표시됩니다.

1
2
3
Traceback (most recent call last):
  File "/home/labex/project/stop_iteration.py", line 10, in <module>
    print(next(numbers_iterator))  ## What happens here?
StopIteration

이터레이터의 끝에 도달하여 다음 요소를 가져오려고 하면 Python 은 StopIteration 예외를 발생시킵니다. 이것은 더 이상 가져올 요소가 없음을 알리는 표준 방법입니다.

try-except 를 사용하여 StopIteration 처리하기

try-except 블록을 사용하여 StopIteration 예외를 처리하도록 코드를 수정해 보겠습니다. stop_iteration.py를 이 코드로 업데이트합니다.

## Create a small list
numbers = [1, 2, 3]

## Convert the list to an iterator
numbers_iterator = iter(numbers)

## Try to retrieve elements safely
try:
    print(next(numbers_iterator))  ## 1
    print(next(numbers_iterator))  ## 2
    print(next(numbers_iterator))  ## 3
    print(next(numbers_iterator))  ## Will raise StopIteration
except StopIteration:
    print("End of iterator reached!")

print("Program continues after exception handling")

업데이트된 코드를 실행합니다.

python3 ~/project/stop_iteration.py

이제 다음을 볼 수 있습니다.

1
2
3
End of iterator reached!
Program continues after exception handling

try-except 블록은 StopIteration 예외를 포착하여 프로그램이 원활하게 계속 실행되도록 합니다.

next() 에서 기본 매개변수 사용하기

Python 은 이터레이터의 끝을 처리하는 더 우아한 방법을 제공합니다. next() 함수는 이터레이터가 소진되었을 때 반환할 기본값을 지정하는 선택적 두 번째 매개변수를 허용합니다.

next_default.py라는 새 파일을 생성합니다.

## Create a small list
numbers = [1, 2, 3]

## Convert the list to an iterator
numbers_iterator = iter(numbers)

## Use default value with next()
print(next(numbers_iterator, "End reached"))  ## 1
print(next(numbers_iterator, "End reached"))  ## 2
print(next(numbers_iterator, "End reached"))  ## 3
print(next(numbers_iterator, "End reached"))  ## Will return the default value
print(next(numbers_iterator, "End reached"))  ## Will return the default value again

코드를 실행합니다.

python3 ~/project/next_default.py

다음과 같은 결과를 볼 수 있습니다.

1
2
3
End reached
End reached

예외를 발생시키는 대신, next()는 더 이상 요소가 없을 때 기본값 "End reached"를 반환합니다.

실용적인 예: 이터레이터 순환

next()를 while 루프와 함께 사용하여 이터레이터의 항목을 처리하는 더 실용적인 예제를 만들어 보겠습니다. iterator_loop.py라는 파일을 생성합니다.

## Create a list of temperatures (in Celsius)
temperatures_celsius = [22, 28, 19, 32, 25, 17]

## Create an iterator
temp_iterator = iter(temperatures_celsius)

## Convert Celsius to Fahrenheit using the iterator
print("Temperature Conversion (Celsius to Fahrenheit):")
print("-" * 45)
print("Celsius\tFahrenheit")
print("-" * 45)

## Loop through the iterator with next() and default value
while True:
    celsius = next(temp_iterator, None)
    if celsius is None:
        break

    ## Convert to Fahrenheit: (C × 9/5) + 32
    fahrenheit = (celsius * 9/5) + 32
    print(f"{celsius}°C\t{fahrenheit:.1f}°F")

print("-" * 45)
print("Conversion complete!")

코드를 실행합니다.

python3 ~/project/iterator_loop.py

다음과 같은 결과를 볼 수 있습니다.

Temperature Conversion (Celsius to Fahrenheit):
---------------------------------------------
Celsius	Fahrenheit
---------------------------------------------
22°C	71.6°F
28°C	82.4°F
19°C	66.2°F
32°C	89.6°F
25°C	77.0°F
17°C	62.6°F
---------------------------------------------
Conversion complete!

이 예제는 next()를 기본값과 함께 사용하여 이터레이터를 제어된 방식으로 순환하는 방법을 보여줍니다. 이터레이터가 소진되면 next()None을 반환하고 루프를 종료합니다.

사용자 정의 이터레이터 생성

이제 기존 반복 가능한 객체와 함께 내장 next() 함수를 사용하는 방법을 이해했으므로, 자신만의 사용자 정의 이터레이터를 만드는 방법을 배우겠습니다.

이터레이터 프로토콜 이해

사용자 정의 이터레이터를 만들려면 두 가지 특수 메서드를 구현해야 합니다.

  1. __iter__(): 이터레이터 객체 자체를 반환합니다.
  2. __next__(): 시퀀스의 다음 항목을 반환하거나 더 이상 항목이 없을 때 StopIteration을 발생시킵니다.

지정된 숫자까지 세는 간단한 사용자 정의 이터레이터를 만들어 보겠습니다. custom_iterator.py라는 새 파일을 생성합니다.

class CountUpIterator:
    """A simple iterator that counts up from 1 to a specified limit."""

    def __init__(self, limit):
        """Initialize the iterator with a limit."""
        self.limit = limit
        self.current = 0

    def __iter__(self):
        """Return the iterator object itself."""
        return self

    def __next__(self):
        """Return the next value in the sequence."""
        self.current += 1
        if self.current <= self.limit:
            return self.current
        else:
            ## No more items
            raise StopIteration

## Create an instance of our custom iterator
counter = CountUpIterator(5)

## Use the next() function with our iterator
print("Counting up:")
print(next(counter))  ## 1
print(next(counter))  ## 2
print(next(counter))  ## 3
print(next(counter))  ## 4
print(next(counter))  ## 5

## This will raise StopIteration
try:
    print(next(counter))
except StopIteration:
    print("Reached the end of the counter!")

## We can also use it in a for loop
print("\nUsing the iterator in a for loop:")
for num in CountUpIterator(3):
    print(num)

코드를 실행합니다.

python3 ~/project/custom_iterator.py

다음과 같은 결과를 볼 수 있습니다.

Counting up:
1
2
3
4
5
Reached the end of the counter!

Using the iterator in a for loop:
1
2
3

사용자 정의 이터레이터 작동 방식

무슨 일이 일어나는지 이해해 보겠습니다.

  1. CountUpIterator 클래스는 __iter__()__next__() 메서드를 사용하여 이터레이터 프로토콜을 구현합니다.
  2. next(counter)를 호출하면 Python 은 이터레이터의 __next__() 메서드를 호출합니다.
  3. __next__()를 호출할 때마다 카운터가 증가하고 새 값을 반환합니다.
  4. 카운터가 제한을 초과하면 StopIteration을 발생시킵니다.
  5. for 루프는 자동으로 StopIteration 예외를 처리하므로 for 루프에서 이터레이터를 직접 사용할 수 있습니다.

더 유용한 이터레이터 생성: 피보나치 수열

지정된 제한까지 피보나치 수열을 생성하는 더 흥미로운 이터레이터를 만들어 보겠습니다. fibonacci_iterator.py라는 파일을 생성합니다.

class FibonacciIterator:
    """Iterator that generates Fibonacci numbers up to a specified limit."""

    def __init__(self, max_value):
        """Initialize with a maximum value."""
        self.max_value = max_value
        self.a, self.b = 0, 1
        self.count = 0

    def __iter__(self):
        """Return the iterator object itself."""
        return self

    def __next__(self):
        """Return the next Fibonacci number."""
        ## First number in sequence
        if self.count == 0:
            self.count += 1
            return self.a

        ## Second number in sequence
        if self.count == 1:
            self.count += 1
            return self.b

        ## Generate the next Fibonacci number
        next_value = self.a + self.b

        ## Stop if we exceed the maximum value
        if next_value > self.max_value:
            raise StopIteration

        ## Update the values for the next iteration
        self.a, self.b = self.b, next_value
        self.count += 1

        return next_value

## Create a Fibonacci iterator that generates numbers up to 100
fib = FibonacciIterator(100)

## Print the Fibonacci sequence
print("Fibonacci sequence up to 100:")
while True:
    try:
        number = next(fib)
        print(number, end=" ")
    except StopIteration:
        break

print("\n\nUsing the same iterator in a for loop:")
## Note: we need to create a new iterator since the previous one is exhausted
for num in FibonacciIterator(100):
    print(num, end=" ")
print()

코드를 실행합니다.

python3 ~/project/fibonacci_iterator.py

다음과 같은 결과를 볼 수 있습니다.

Fibonacci sequence up to 100:
0 1 1 2 3 5 8 13 21 34 55 89

Using the same iterator in a for loop:
0 1 1 2 3 5 8 13 21 34 55 89

실용적인 연습: 파일 라인 이터레이터 생성

대용량 파일을 처리할 때 유용할 수 있는, 파일을 한 번에 한 줄씩 읽는 실용적인 이터레이터를 만들어 보겠습니다. 먼저, 샘플 텍스트 파일을 만들어 보겠습니다.

  1. sample.txt라는 새 파일을 생성합니다.
This is line 1 of our sample file.
Python iterators are powerful tools.
They allow you to process data one item at a time.
This is efficient for large datasets.
The end!
  1. 이제 file_iterator.py라는 파일을 생성합니다.
class FileLineIterator:
    """Iterator that reads lines from a file one at a time."""

    def __init__(self, filename):
        """Initialize with a filename."""
        self.filename = filename
        self.file = None

    def __iter__(self):
        """Open the file and return the iterator."""
        self.file = open(self.filename, 'r')
        return self

    def __next__(self):
        """Read the next line from the file."""
        if self.file is None:
            raise StopIteration

        line = self.file.readline()

        if not line:  ## Empty string indicates end of file
            self.file.close()
            self.file = None
            raise StopIteration

        return line.strip()  ## Remove trailing newline

    def __del__(self):
        """Ensure the file is closed when the iterator is garbage collected."""
        if self.file is not None:
            self.file.close()

## Create a file iterator
line_iterator = FileLineIterator('/home/labex/project/sample.txt')

## Read lines one by one
print("Reading file line by line:")
print("-" * 30)

try:
    line_number = 1
    while True:
        line = next(line_iterator)
        print(f"Line {line_number}: {line}")
        line_number += 1
except StopIteration:
    print("-" * 30)
    print("End of file reached!")

## Read the file again using a for loop
print("\nReading file with for loop:")
print("-" * 30)
for i, line in enumerate(FileLineIterator('/home/labex/project/sample.txt'), 1):
    print(f"Line {i}: {line}")
print("-" * 30)

코드를 실행합니다.

python3 ~/project/file_iterator.py

다음과 같은 결과를 볼 수 있습니다.

Reading file line by line:
------------------------------
Line 1: This is line 1 of our sample file.
Line 2: Python iterators are powerful tools.
Line 3: They allow you to process data one item at a time.
Line 4: This is efficient for large datasets.
Line 5: The end!
------------------------------
End of file reached!

Reading file with for loop:
------------------------------
Line 1: This is line 1 of our sample file.
Line 2: Python iterators are powerful tools.
Line 3: They allow you to process data one item at a time.
Line 4: This is efficient for large datasets.
Line 5: The end!
------------------------------

이 파일 라인 이터레이터는 이터레이터의 실제 사용을 보여줍니다. 전체 파일을 메모리에 로드하지 않고도 파일을 한 줄씩 처리할 수 있으므로 대용량 파일에 특히 유용합니다.

이터레이터의 실제 사용 사례

이제 이터레이터를 만들고 사용하는 방법을 이해했으므로, 이터레이터가 코드를 개선할 수 있는 몇 가지 실용적인 실제 사용 사례를 살펴보겠습니다.

제너레이터를 사용한 지연 평가

제너레이터는 yield 문을 사용하는 함수로 생성된 특수한 유형의 이터레이터입니다. 이를 통해 값을 즉시 생성할 수 있으며, 이는 전체 목록을 만드는 것보다 메모리 효율적일 수 있습니다.

generator_example.py라는 파일을 생성합니다.

def squared_numbers(n):
    """Generate squares of numbers from 1 to n."""
    for i in range(1, n + 1):
        yield i * i

## Create a generator for squares of numbers 1 to 10
squares = squared_numbers(10)

## squares is a generator object (a type of iterator)
print(f"Type of squares: {type(squares)}")

## Use next() to get values from the generator
print("\nGetting values with next():")
print(next(squares))  ## 1
print(next(squares))  ## 4
print(next(squares))  ## 9

## Use a for loop to get the remaining values
print("\nGetting remaining values with a for loop:")
for square in squares:
    print(square)

## The generator is now exhausted, so this won't print anything
print("\nTrying to get more values (generator is exhausted):")
for square in squares:
    print(square)

## Create a new generator and convert all values to a list at once
all_squares = list(squared_numbers(10))
print(f"\nAll squares as a list: {all_squares}")

코드를 실행합니다.

python3 ~/project/generator_example.py

다음과 같은 결과를 볼 수 있습니다.

Type of squares: <class 'generator'>

Getting values with next():
1
4
9

Getting remaining values with a for loop:
16
25
36
49
64
81
100

Trying to get more values (generator is exhausted):

All squares as a list: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

제너레이터는 간단한 경우에 이터레이터를 만드는 더 간결한 방법입니다. 제너레이터는 자동으로 이터레이터 프로토콜을 구현합니다.

대용량 데이터 세트 처리

이터레이터는 한 번에 하나의 요소로 작업할 수 있으므로 대용량 데이터 세트를 처리하는 데 적합합니다. 온도에 대한 대용량 데이터 세트를 시뮬레이션하는 예제를 만들어 보겠습니다.

data_processing.py라는 파일을 생성합니다.

import random
import time

def temperature_data_generator(days, start_temp=15.0, max_variation=5.0):
    """Generate simulated hourly temperature data for a number of days."""
    hours_per_day = 24
    total_hours = days * hours_per_day

    current_temp = start_temp

    for hour in range(total_hours):
        ## Simulate temperature variations
        day_progress = (hour % hours_per_day) / hours_per_day  ## 0.0 to 1.0 through the day

        ## Temperature is generally cooler at night, warmer during day
        time_factor = -max_variation/2 * (
            -2 * day_progress + 1 if day_progress < 0.5
            else 2 * day_progress - 1
        )

        ## Add some randomness
        random_factor = random.uniform(-1.0, 1.0)

        current_temp += time_factor + random_factor
        current_temp = max(0, min(40, current_temp))  ## Keep between 0-40°C

        yield (hour // hours_per_day, hour % hours_per_day, round(current_temp, 1))

def process_temperature_data():
    """Process a large set of temperature data using an iterator."""
    print("Processing hourly temperature data for 30 days...")
    print("-" * 50)

    ## Create our data generator
    data_iterator = temperature_data_generator(days=30)

    ## Track some statistics
    total_readings = 0
    temp_sum = 0
    min_temp = float('inf')
    max_temp = float('-inf')

    ## Process the data one reading at a time
    start_time = time.time()

    for day, hour, temp in data_iterator:
        ## Update statistics
        total_readings += 1
        temp_sum += temp
        min_temp = min(min_temp, temp)
        max_temp = max(max_temp, temp)

        ## Just for demonstration, print a reading every 24 hours
        if hour == 12:  ## Noon each day
            print(f"Day {day+1}, 12:00 PM: {temp}°C")

    processing_time = time.time() - start_time

    ## Calculate final statistics
    avg_temp = temp_sum / total_readings if total_readings > 0 else 0

    print("-" * 50)
    print(f"Processed {total_readings} temperature readings in {processing_time:.3f} seconds")
    print(f"Average temperature: {avg_temp:.1f}°C")
    print(f"Temperature range: {min_temp:.1f}°C to {max_temp:.1f}°C")

## Run the temperature data processing
process_temperature_data()

코드를 실행합니다.

python3 ~/project/data_processing.py

다음과 유사한 출력을 볼 수 있습니다 (정확한 온도는 무작위성으로 인해 달라집니다).

Processing hourly temperature data for 30 days...
--------------------------------------------------
Day 1, 12:00 PM: 17.5°C
Day 2, 12:00 PM: 18.1°C
Day 3, 12:00 PM: 17.3°C
...
Day 30, 12:00 PM: 19.7°C
--------------------------------------------------
Processed 720 temperature readings in 0.012 seconds
Average temperature: 18.2°C
Temperature range: 12.3°C to 24.7°C

이 예제에서는 이터레이터를 사용하여 720 개의 온도 판독값 (24 시간 × 30 일) 의 시뮬레이션된 데이터 세트를 한 번에 메모리에 모든 데이터를 저장하지 않고 처리하고 있습니다. 이터레이터는 각 판독값을 필요에 따라 생성하여 코드를 더 메모리 효율적으로 만듭니다.

이터레이터를 사용한 데이터 파이프라인 구축

이터레이터를 함께 연결하여 데이터 처리 파이프라인을 만들 수 있습니다. 다음 파이프라인을 구축해 보겠습니다.

  1. 숫자를 생성합니다.
  2. 홀수를 필터링합니다.
  3. 나머지 짝수를 제곱합니다.
  4. 출력을 특정 결과 수로 제한합니다.

data_pipeline.py라는 파일을 생성합니다.

def generate_numbers(start, end):
    """Generate numbers in the given range."""
    print(f"Starting generator from {start} to {end}")
    for i in range(start, end + 1):
        print(f"Generating: {i}")
        yield i

def filter_even(numbers):
    """Filter for even numbers only."""
    for num in numbers:
        if num % 2 == 0:
            print(f"Filtering: {num} is even")
            yield num
        else:
            print(f"Filtering: {num} is odd (skipped)")

def square_numbers(numbers):
    """Square each number."""
    for num in numbers:
        squared = num ** 2
        print(f"Squaring: {num} → {squared}")
        yield squared

def limit_results(iterable, max_results):
    """Limit the number of results."""
    count = 0
    for item in iterable:
        if count < max_results:
            print(f"Limiting: keeping item #{count+1}")
            yield item
            count += 1
        else:
            print(f"Limiting: reached maximum of {max_results} items")
            break

## Create our data pipeline
print("Creating data pipeline...\n")

pipeline = (
    limit_results(
        square_numbers(
            filter_even(
                generate_numbers(1, 10)
            )
        ),
        3  ## Limit to 3 results
    )
)

## Execute the pipeline by iterating through it
print("\nExecuting pipeline and collecting results:")
print("-" * 50)
results = list(pipeline)
print("-" * 50)

print(f"\nFinal results: {results}")

코드를 실행합니다.

python3 ~/project/data_pipeline.py

다음과 같은 결과를 볼 수 있습니다.

Creating data pipeline...

Executing pipeline and collecting results:
--------------------------------------------------
Starting generator from 1 to 10
Generating: 1
Filtering: 1 is odd (skipped)
Generating: 2
Filtering: 2 is even
Squaring: 2 → 4
Limiting: keeping item #1
Generating: 3
Filtering: 3 is odd (skipped)
Generating: 4
Filtering: 4 is even
Squaring: 4 → 16
Limiting: keeping item #2
Generating: 5
Filtering: 5 is odd (skipped)
Generating: 6
Filtering: 6 is even
Squaring: 6 → 36
Limiting: keeping item #3
Generating: 7
Filtering: 7 is odd (skipped)
Generating: 8
Filtering: 8 is even
Squaring: 8 → 64
Limiting: reached maximum of 3 items
--------------------------------------------------

Final results: [4, 16, 36]

이 파이프라인 예제는 이터레이터를 함께 연결하여 데이터 처리 워크플로를 형성하는 방법을 보여줍니다. 파이프라인의 각 단계는 한 번에 하나의 항목을 처리하여 다음 단계로 전달합니다. 파이프라인은 실제로 결과를 사용할 때까지 (이 경우 목록으로 변환하여) 데이터를 처리하지 않습니다.

주요 장점은 파이프라인 단계 사이에 중간 목록이 생성되지 않아 대용량 데이터 세트에서도 이 접근 방식이 메모리 효율적이라는 것입니다.

요약

이 튜토리얼에서는 Python 이터레이터와 next() 함수를 효과적으로 사용하는 방법을 배웠습니다. 다룬 주요 개념은 다음과 같습니다.

  1. 기본 이터레이터 (Basic Iterators): 기존 컬렉션에서 이터레이터를 생성하고 next()를 사용하여 한 번에 하나씩 요소를 검색합니다.

  2. 예외 처리 (Exception Handling): 이터레이터가 소진될 때 발생하는 StopIteration 예외를 관리하고, 대체 값을 제공하기 위해 next()와 함께 기본값을 사용합니다.

  3. 사용자 정의 이터레이터 (Custom Iterators): __iter__()__next__() 메서드를 구현하여 사용자 정의 이터레이터 클래스를 생성하여 사용자 정의 데이터 시퀀스를 생성할 수 있습니다.

  4. 실제 사용 사례 (Real-World Applications): 효율적인 데이터 처리, 제너레이터를 사용한 지연 평가, 데이터 처리 파이프라인 구축을 위해 이터레이터를 사용합니다.

이러한 이터레이터 기술은 특히 대용량 데이터 세트로 작업할 때 메모리 효율적이고 확장 가능한 Python 코드를 작성하는 데 필수적입니다. 모든 것을 메모리에 로드하지 않고 한 번에 하나의 요소를 처리하는 기능은 이터레이터를 Python 프로그래머의 도구 상자에서 매우 귀중한 도구로 만듭니다.