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
Title-Author-data
Python Regular Expressions (RegEx) Basic Matching 12
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Timer and Time Measurement (time module) 8
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Iterators (Iterator Usage) 10
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Inheritance (OOP) 5
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Classes and Object Creation (OOP) 8
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Dictionary Sorting (By Key / By Value) 4
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Logging Implementation 4
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Exception Handling (try-except) 8
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python CSV File Reading and Processing 5
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python JSON Data Handling (Read/Write) 6
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python File Reading and Writing (Text Files) 3
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Decorators: Implementation and Usage 11
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Generators: Implementation and Usage 6
no_profile mrkorea쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Lambda Functions 9
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New
Python Remove Duplicate Elements from a List 10
no_profile goposu쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물
09-29 New

visit

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