DEV Community

Bekzod
Bekzod

Posted on

Iterator va generator

Iterator

Python da iterator obyektlar __iter__ va __next__ metodlari orqali amalga oshiriladi. Iterator obyektni iterable tiplar list, tuple, dict, str va boshqa, iter() built_in metodi orqali yaratamiz va elementlarni olishda next() metodidan foydalanamiz.
iterator
Manba: Codingninjas

my_list = [2, 4, 8, 16, 32]

iterator = iter(my_list)

print(next(iterator))  # 2
print(next(iterator))  # 4
print(next(iterator))  # 8
print(next(iterator))  # 16
print(next(iterator))  # 32
print(next(iterator))  # StopIteration
Enter fullscreen mode Exit fullscreen mode

Iterator oxirgi elementidan keyin next ishlatilsa StopIteration xatolik qaytaradi.

Xuddi shuni for loop orqali amalga oshiramiz.

my_list = [2, 4, 8, 16, 32]

for item in my_list:
    print(item)

# 2
# 4
# 8
# 16
# 32
Enter fullscreen mode Exit fullscreen mode

Iterator obyekt elementlarini for loop orqali ham olishimiz mumkin.

my_list = [2, 4, 8, 16, 32]

iterator = iter(my_list)

for item in iterator:
    print(item)

# 2
# 4
# 8
# 16
# 32
Enter fullscreen mode Exit fullscreen mode

__iter__ va __next__ metodlarni o'zgartirgan holda iterator obyekt yaratamiz.

class PowTwo:
    def __init__(self, limit=0):
        self.limit = limit

    def __iter__(self):
        self.n = 1
        return self

    def __next__(self):
        if self.n <= self.limit:
            pow_number = 2 ** self.n
            self.n += 1
            return pow_number
        else:
            raise StopIteration


numbers = PowTwo(5)
iterator = iter(numbers)

print(next(iterator))  # 2
print(next(iterator))  # 4
print(next(iterator))  # 8
print(next(iterator))  # 16
print(next(iterator))  # 32
print(next(iterator))  # StopIteration
Enter fullscreen mode Exit fullscreen mode

iter() va next() built_in metodlar ishlatganimizda class da yozilgan __iter__ va __next__ metodlarga murojaat qilinadi.

numbers = PowTwo(5)
iterator = numbers.__iter__()

print(iterator.__next__())  # 2
print(iterator.__next__())  # 4
print(iterator.__next__())  # 8
print(iterator.__next__())  # 16
print(iterator.__next__())  # 32
print(iterator.__next__())  # StopIteration
Enter fullscreen mode Exit fullscreen mode

Generator

generatorManba: Medium

Python da generator funksiya oddiy funksiyadek bo'ladi, faqat yield kalit so'zi orqali qiymat qaytariladi.

def generator():
    yield 1
    yield 2
    yield 3


for value in generator():
    print(value)
# 1
# 2
# 3
Enter fullscreen mode Exit fullscreen mode

Generator funksiya generator obyekt qaytaradi.

print(generator())
# <generator object generator at 0x7f1af486aea0>
Enter fullscreen mode Exit fullscreen mode

Generator obyekt dan iterator sifatida foydalanib next() orqali ham qiymatlarni olishimiz mumkin.

my_generator = generator()

print(next(my_generator))  # 1
print(next(my_generator))  # 2
print(next(my_generator))  # 3
print(next(my_generator))  # StopIteration
Enter fullscreen mode Exit fullscreen mode

Nima uchun funksiyada return o'rniga yield ishlatilyapti?

return funksiyada berilgan qiymatni qaytaradi, yield esa ketma-ketlikni qaytarib yuboradi. Biz funksiyada butun bir ketma-ketlik xotirada saqlamasdan qaytarmoqchi bo'lsak yield foydalanishimiz kerak.

Raqamlar ro'yxatidan ularning kvadratlarini qaytaradigan generator funksiya yaratib ko'ramiz.

def square(nums):
    for num in nums:
        yield num ** 2


numbers = [1, 2, 3]
generator = square(numbers)

print(next(generator))  # 1
print(next(generator))  # 4
print(next(generator))  # 9
print(next(generator))  # StopIteration
Enter fullscreen mode Exit fullscreen mode

Generator funksiya orqali qaytariladigan ketma-ketlikni sum() va boshqa iterable qabul qiladigan funksiyalar orqali ishlatsak ham bo'ladi.

numbers = [1, 2, 3]
sum_of_square_numbers = sum(square(numbers))
print(sum_of_square_numbers)  # 14
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
saidahror13 profile image
Saidahror

👍👍👍