iterators vs iterables

nara_lee·2025년 4월 15일
1
post-thumbnail

🔁 Iterable

An iterable is any object that you can loop over with a for loop.
Examples include:

  • list, tuple, str, set, dict
  • Basically, if it implements the __iter__() method, it’s iterable.

➡️ But it doesn’t remember where it is in the iteration — it just gives you an iterator.

my_list = [1, 2, 3]
iter_obj = iter(my_list)  # Calling iter() on iterable returns an iterator

▶️ Iterator

An iterator is an object that does the actual iterating.
It:

  • Implements both __iter__() and __next__() methods
  • Keeps track of where it is in the sequence
  • Raises StopIteration when it's done
next(iter_obj)  # Returns 1
next(iter_obj)  # Returns 2
next(iter_obj)  # Returns 3
next(iter_obj)  # Raises StopIteration

✅ Key Differences:

FeatureIterableIterator
PurposeCan be looped overActually performs looping
Has __iter__()✅ Yes✅ Yes
Has __next__()❌ No✅ Yes
Reusable✅ Yes (you can create a new iterator from it)❌ No (once used up, it's done)
Examplelist, tuple, strObject returned by iter()

💡 Summary:

  • Iterable = "Can I get an iterator from this?"
  • Iterator = "Can I get the next item myself?"

본 후기는 [한글과컴퓨터x한국생산성본부x스나이퍼팩토리] 한컴 AI 아카데미 (B-log) 리뷰로 작성 되었습니다.

#한컴AI아카데미 #AI개발자 #AI개발자교육 #한글과컴퓨터 #한국생산성본부 #스나이퍼팩토리 #부트캠프 #AI전문가양성 #개발자교육 #개발자취업

0개의 댓글