Python İteratorlar | Iterators in Python | iter #kody_az
Dərs haqqında
Python-da iterator obyektləri, kolleksiyadakı (məsələn, siyahı və ya tupl kimi) elementləri indeksləşdirmədən keçməyə imkan verən obyektlərdir.
Iteratorlar Necə İşləyir
1) Dövr (məsələn, for dövr) kolleksiya üzərində keçid edərkən, Python iterator protokolundan istifadə edir.
2) for dövrü obyekt üzərində daxildə iter() funksiyasını çağırır və bu da iterator qaytarır.
3) Dövr sonra iterator üzərində next() funksiyasını təkrarlayaraq hər elementi alır, ta ki StopIteration istisnası qaldırılana qədər.
Əsas məqamlar
• Yaddaş Effektivliyi:
Iteratorlar yaddaş cəhətdən effektivdir, çünki onlar elementləri birdən-birə yox, bir-bir qaytarırlar.
• Tənbəl Qiymətləndirmə (Lazy Evaluation):
Iteratorlar, yalnız tələb olunduqda dəyərləri hesablama və qaytarma üstünlüyü təmin edir.
• Təkrar İstifadə Olunmazlıq:
Iteratorlar təkrar istifadə edilə bilməzlər. Bir iterator tükəndikdə (yəni StopIteration qaldırıldıqda), onu yenidən istifadə etmək mümkün deyil. Yenidən keçmək üçün yeni bir iterator yaratmaq lazımdır.
Python, iterator qaytaran daxili funksiyalar təqdim edir, məsələn, enumerate(), zip(), iter() və s.
========
In Python, an iterator is an object that allows you to traverse through all the elements of a collection (such as a list or tuple) without needing to use indexing.
How Iterators Work
• When you use a loop (like a for loop) to traverse through a collection, Python uses the iterator protocol behind the scenes.
• The for loop implicitly calls the iter() function on the object, which returns an iterator.
• The loop then repeatedly calls the next() function on the iterator to get each element until StopIteration is raised.
Key Points
• Memory Efficiency: Iterators are memory efficient because they yield items one at a time rather than storing all elements in memory at once.
• Lazy Evaluation: Iterators provide lazy evaluation, which means values are computed and returned only when requested.
• Reusability: Iterators are not inherently reusable. Once an iterator has been exhausted (i.e., StopIteration is raised), it cannot be reset or reused. You would need to create a new iterator to traverse the collection again.
Python provides built-in functions that return iterators, such as enumerate(), zip(), iter(), and many others.