[python 기초] iterators

EMMA·2022년 3월 7일
0

파이썬을 다루다 보면, 'iterable'라는 단어를 많이 접하게 된다.
stackoverflow에서 찾아보면, iteration/iterable/iterator의 뜻은 아래와 같이 정리할 수 있겠다.

  • iteration: a general term for taking each item of something, one after another (반복, loop)
  • iterable: __iter__ 함수를 갖고 있어 loop가 가능
  • iterator: iterable에서 __next__를 가지고 순차적으로 요소를 호출할 수 있는 객체

참고로, next() 는 python2 버전이고, python3에서는 __next__ 로 바뀌었다고 한다. (어쩐지...왜 next() 만 있나 했더니 내가 2.xx 버전 python을 깔아서였다;)

*참고 내용: https://stackoverflow.com/a/9884259

iterator는 순차적으로 요소를 호출할 수 있는 객체를 말한다.
간단하게 확인하는 방법은, dir를 사용해 객체의 내장함수에 __iter__가 있는지 보면 된다.

L = [1,2,3]
print(dir(L))
> L안에 있는 내장 함수 확인 가능, __iter__가 있으면 L은 iterator 객체가 맞음 
L = [1,2,3]
#iterator 객체임을 확인 (최초 호출 개념)
print(L.__iter__())

#객체의 요소를 하나씩 꺼내려면 
print(L.__next__())	>1
print(L.__next__())	>2
print(L.__next__())	>3
print(L.__next__())	>#StopIteration 

__init__, __next__를 더 쉽게 작성하는 방법은 init(), next() 사용

L = [1,2,3,4]
I = iter(L)

while True:
	try:
    	X = next(I)
    except stopIteration:
    	break
    print(X**2)

>1,4,9,16

dictionary 또한 iterable한 객체이기 때문에, 위 예시를 적용할 수 있다.

D = {'a':1, 'b':2, 'c':3}
for key in D.keys():
    print(key)

이를 while문과 init(), next() 를 사용하면 아래와 같다.

D = {'a':1, 'b':2, 'c':3}
I = iter(D)
while True:
	try:
    	key = next(I)
    except StopIteration:
    	break
    print(key)

>a,c,b
profile
예비 개발자의 기술 블로그 | explore, explore and explore

0개의 댓글