2019.04.04 - [Python.Iterable] iterable, iterator 차이, islice, yield from, nested list comprehension

1. iterable 과 iterator의 차이

1) iterable

정의 : An object capable of returning its members one at a time. 


- 가장 대표적인 예로는 sequence type인 list, str, tuple 이 대표적이다. 
- 이들은 sequence 타입인데 single element를 하나씩 차례대로 반환할 수 있다.
- iter(a: list)로 선언한 뒤에 next(a: list)를 하면 a 안에 있는 값을 하나씩 리턴받을 수 있다.

2) iterator

정의 : An object representing a stream of data. Repeated calls to the iterator’s next() method return successive items in the stream. 

- 가장 대표적인 예로는 generator가 될 것 같다.
- next()를 이용해서 커서가 sequence를 한 칸씩 뒤로 이동하며 값을 호출하고, 끝에 도달하면 StopIteration 에러를 발생시킨다.

그렇다면 list는 next(list)하면 에러가 발생하는데 어째서 for문에서는 잘 동작하는거지?! 

-> 답은 list를 for문에 집어넣으면 for문이 자동적으로 iter(리스트: list)를 해주기 때문이다.

참고: https://bluese05.tistory.com/55


2. itertool의 islice

# islice(iterator|iterable, start, end, step)
from itertools import islice
l = range(0, 10)
result = islice(l, 0, 5)
list(result)
list(result)

# islice는 lazy iterator다 == generator로, 값을 리턴하고 나면 consume 되어버리는 녀석이라서 두번째 list(result)는 값이 없다.

3. yield from 복습

아래 두 개는 결과가 같다.

def read_all_data():
    global a, b, c
    for items in (a, b, c):
        for item in items:
            yield item
           
def read_all_data2():
    for items in (a, b, c):
        yield from items

즉, yield from items는 iteratable한 객체를 iterate하며 each element를 yield 하는 것이다.
(그러려면 for문이나 iterate중인 구문 안에 있어야겠지?)

4. Nested List comprehension 복습

matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# 이것과
flatten_matrix = []
  
for sublist in matrix:
    for val in sublist:
        flatten_matrix.append(val)
          
print(flatten_matrix)


# 이것은 같다
flatten_matrix = [val for sublist in matrix for val in sublist]
print(flatten_matrix)

즉, list comprehension 가장 전방에 나오는 값은 최종 리턴되는 값이고 그 뒤의 for문 부터는 가장 outer부터 쌓이게 되는 것이다.


댓글

이 블로그의 인기 게시물

로컬 Tomcat 서버 실행속도 개선

2019.05.23 - SQLAlchemy 의 객체 상태 관리 (expire, refresh, flush, commit) 에 관한 이해

2020.02.17 Python의 multiprocessing 중 Pool.map(), chunksize에 관한 내용