Python Iterators (Iterator Usage) > Python

Entire search within the site

Python

Python Iterators (Iterator Usage)

Page Info

Content

Python Iterators (Iterator Usage)

In Python, an iterator is an object that allows you to traverse through all elements of a collection (like lists, tuples, or dictionaries) one by one, without exposing the underlying structure. Iterators are implemented using the __iter__() and __next__() methods.

Creating and Using an Iterator


# A simple list
my_list = [10, 20, 30]

# Get an iterator from the list
it = iter(my_list)

# Access elements using next()
print(next(it))  # Output: 10
print(next(it))  # Output: 20
print(next(it))  # Output: 30
# next(it) would raise StopIteration if called again
  

Explanation:

  • iter(my_list): Returns an iterator object for the list.
  • next(it): Returns the next element from the iterator.
  • StopIteration: Raised when there are no more elements to iterate.

Using Iterators in a Loop


my_list = [1, 2, 3, 4, 5]

# For loop automatically handles the iterator
for item in my_list:
    print(item)
# Output: 1 2 3 4 5
  

Explanation:

  • A for loop internally creates an iterator and calls next() until StopIteration is raised.
  • This is the most common way to use iterators in Python.

Creating a Custom Iterator


# Custom iterator class
class MyNumbers:
    def __init__(self, max):
        self.max = max
        self.num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.num < self.max:
            current = self.num
            self.num += 1
            return current
        else:
            raise StopIteration

# Using the custom iterator
numbers = MyNumbers(5)
for n in numbers:
    print(n)
# Output: 0 1 2 3 4
  

Key Points

  • Iterator: An object with __iter__() and __next__() methods.
  • iter(): Used to get an iterator from an iterable.
  • next(): Used to get the next element from an iterator.
  • StopIteration: Signals that iteration is complete.
  • Custom iterators allow fine-grained control over how elements are generated or returned.

SEO Keywords

Python iterator example, Python next() function, Python __iter__ __next__, Python custom iterator, Python for loop iterator, Python iterable

Using iterators in Python enables efficient traversal of data collections and supports lazy evaluation, which is particularly useful for large datasets.

Good0 Bad0

댓글목록

등록된 댓글이 없습니다.

Python

Latest Posts

Total 31 posts | Page 1
Python List
No Title Author Views Likes Dislikes Date
31 Python Regular Expressions (RegEx) Basic Matching New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 11 0 0 09-29
30 Python Timer and Time Measurement (time module) New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 8 0 0 09-29
29 Python Iterators (Iterator Usage) New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 6 0 0 09-29
28 Python Inheritance (OOP) New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4 0 0 09-29
27 Python Classes and Object Creation (OOP) New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 7 0 0 09-29
26 Python Dictionary Sorting (By Key / By Value) New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4 0 0 09-29
25 Python Logging Implementation New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 3 0 0 09-29
24 Python Exception Handling (try-except) New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 4 0 0 09-29
23 Python CSV File Reading and Processing New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5 0 0 09-29
22 Python JSON Data Handling (Read/Write) New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5 0 0 09-29
21 Python File Reading and Writing (Text Files) New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 3 0 0 09-29
20 Python Decorators: Implementation and Usage New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 8 0 0 09-29
19 Python Generators: Implementation and Usage New no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 5 0 0 09-29
18 Python Lambda Functions New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 8 0 0 09-29
17 Python Remove Duplicate Elements from a List New no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 10 0 0 09-29

visit

today
52
yesday
144
maxday
144
allday
196
Copyright © https://goposu.com/g All rights reserved.