python#1 파이썬의 반복 가능한 객체들에 대해서

Clay Ryu's sound lab·2021년 12월 8일
0

Framework

목록 보기
5/48

시퀀스 객체와 반복 가능한 객체의 차이

  • 반복 가능한 객체는 시퀀스를 포괄하는 상위 개념이라 볼 수 있다.
  • 리스트, 튜플, range, 문자열은 시퀀스 객체이다. 그리고 딕셔너리와 세트는 반복 가능한 객체이지만 시퀀스 객체는 아니다.
  • 시퀀스 객체는 요소의 순서가 정해져 있고 연속적(sequence)으로 이어져 있어야 하는데 딕셔너리와 세트는 요소(키)의 순서가 정해져 있지 않기 때문이다.

Iterable 객체

  • iterable 객체는 반복 가능한 객체이며 대표적인 iterable 객체로는 list, str, tuple과 같은 시퀀스 객체와 dict, set와 같은 비시퀀스 객체가 있으며 또한 bytes, range등이 있다.

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an iter() method or with a getitem() method that implements Sequence semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.
https://docs.python.org/3/glossary.html#term-iterable

  • iterable 객체를 판별하기 위해서는 그 객체가 collections.Iterable에 속한 instance인지 확인하면 된다.
  • isinstance 함수는 첫번째 입력값이 두번째로 입력한 클래스의 instance이면 True를 반환한다. 따라서 다음과 같이 탐색해보면
 >>> import collections
    
  # iterable 한 타입
  >>> var_list = [1, 3, 5, 7]
  >>> isinstance(var_list, collections.Iterable)
  True
  >>> var_dict = {"a": 1, "b":1}
  >>> isinstance(var_dict, collections.Iterable)
  True
  >>> var_set = {1, 3}
  >>> isinstance(var_set, collections.Iterable)
  True
  >>> var_str = "abc"
  >>> isinstance(var_str, collections.Iterable)
  True
  >>> var_bytes = b'abcdef'
  >>> isinstance(var_bytes, collections.Iterable)
  True
  >>> var_tuple = (1, 3, 5, 7)
  >>> isinstance(var_tuple, collections.Iterable)
  True
  >>> var_range = range(0,5)
  >>> isinstance(var_range, collections.Iterable)
  True

  # iterable하지 않은 타입
  >>> var_int = 932
  >>> isinstance(var_int, collections.Iterable)
  False
  >>> var_float = 10.2
  >>> isinstance(var_float, collections.Iterable)
  False
  >>> var_none = None
  >>> isinstance(var_none, collections.Iterable)
  False

이와 같은 결과가 나오는 것을 알수 있다. 링크텍스트

profile
chords & code // harmony with structure

0개의 댓글