Level 1 : Circular iterator that loops indefinitely over a list.


class CircularIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if not self.data:
            raise StopIteration
        value = self.data[self.index]
        self.index = (self.index + 1) % len(self.data)
        return value

it = iter(CircularIterator([1, 2, 3]))
for _ in range(5):
    print(next(it), end=" ")

Author: SandhyaR | Tags: iterator | 1859+ Python FAQs | Share
docstring | functions | precedence | file-handling | lambda | handling-missing-values-(fillna,-dropna) | iterable | encoding | exception-handling | lambdas | input-function | directory-operations | global | head-and-tail | basic | comment | using-yield-in-functions | multiple-except-blocks | aggregating-data-with-functools.reduce() | compute | bitwise-operator | numpy | integer | benefit | class | list-mutation | error | mapping-function | difference-between-threads-and-processes | enumerate() | memory-management | dataframe-and-series-objects | goto-function | objects | invalid-list | random-function | decorator | quantifiers-(*,-+,-?,-{}) | operations | module | file_handling | list-slicing | python-module | heap-memory | frozenset | indexing:-loc-vs-iloc | operators | loop-control-statements | list-comprehensions | loops | exception | mathematical-function | control-flow | floats | multiple-inheritance | filter-function | overriding-methods | matplotlib | functional-programming | filter | global-variable | interpreter | numeric | default-arguments | python-syntax-and-structure | list,-set,-and-dictionary-comprehensions | else | input-function | creating-and-starting-threads | postfix | intering | list-method | tuples | formatting-with-strftime | math | feature | pseudocode | working-with-binary-files-(rb,-wb) | global-variable | opening-files-(open()) | tuple-methods | class-and-inheritance | typeerror | thread-synchronization | anchors-(^,-$) | init | type_conversion | call | __all__-attribute | using-join()-and-is_alive()-methods | update | logical-operation | center | fabs-function | def | thread | dictionary-methods | using-else-and-finally | method | walking-through-directories-using-os.walk() | conditional-statements | access-modifier | list-methods-and-slicing | syntax | boolean-and-non-boolean | max-min | raise-statement | lists | nested-loop | function-argument | binary-operation | pandas | list-join | matrix | reading:-read(),-readline(),-readlines() | counter | for | python_version | multithreading | version-check | iterator | swapping | data-type | zfill-function | design-principle | else-statement | descriptors | iterators | counter-function | advanced-file-operations | loop-control | default-mutable-argument | yield | python-django | touples | mutable | error-handling | encapsulation | python | sorting-and-ranking | sys-module | rollback | choice | datetime.date,-datetime.time,-datetime.datetime | random | string-manipulation | __future__ | bitwise | min-function | sorting | map-function | inheritance | shallow-copy | string-iteration | command-line-parsing | asyncio | arithmetic-operation | escape-operator | operand | generator | inherit | function | global-keyword | string-formatting | while-loops | reading-and-writing-files | return-statement | list-vs-tuple | input | generators-in-python | logical-operator | oops | oop | comprehension | arbitrary-arguments-(*args,-**kwargs) | generators | zip | software-design | type-conversion-and-casting | why-use-multiprocessing-over-threading?-(gil) | sorted | bitwise-operator | data-structure | reading-and-writing-large-files-efficiently | matrix-list-comprehension | constructor | recursion | class-and-object | defining-functions | expand-tab | print-statement | working-with-file-paths | test-discovery | destructor | sum-function | precedence-and-associativity | staticmethod | application | formal-and-actual-parameter | dictionary-comprehensions | class-and-instance-variable | pass | string-formatting | conversion | mysql | loop | working-with-temporary-files-using-tempfile | condition | virtual-environment | zip-function | slice | file | class-decorators | multiprocessing | boolean-masking | exponentiation | sets | single-inheritance | string-concatenation | debugging | complex-number | classes | range | dicts | functional-programming | string-slicing | while-else-loop | python-operators | filtering-and-indexing | built-in-modules | gil | introduction-to-multiprocessing | error-handling | virtual-environment | booleans | introduction-to-threads | identity-operator | factorial-function | implementation | decimal | data-type-conversions | managing-directories-with-os-and-shutil | thread-safe-data-structures-(queue.queue) | immutability | stack | scientific-notation | time-series-with-pandas | name-mangling | tuple-unpacking | control-statement | assignment-operators | set | control-flow | arithmetic-expression | lambda-functions | overflow | membership-operators-(in,-not-in) | pep | unit-testing | __init_subclass__ | round | string-method | join | match | floating-point-precision | list-operation | built-in-function | regular-expression | sys | assignment-operator | round-function | async | method-overloading | append | array | string-slicing | integers | datetime | using-assertions-(assertequal,-assertraises) | creating-custom-modules | recurssion | min-max-function | raise | using-map()-for-transformations | literal-characters-and-special-characters | syntax-error | multiple-inheritance | split | syntaxerror | logical-operator | assert | syntax-error | import-method | keyword | type-conversion | methods | list-comprehension | logical-operators | threading | installation | version | variable | regex | conditional-statement | while-and-for-loop | regular-expressions | working-with-dates-and-times | operator-overloading | exception-handling | indentation | complex | boolean | library | string-methods | file-handling | dictionaries | pickling--unpickling | strings | odd-number | identifier | print | key-value-pairs | binary | asyncio-module | static-method | using-the-threading-module | object-attribute | namespace | built-in-function | data-structures-in-python | collection | operator-and | mathematics | format | comparison | function-and-scope | attribute | sum() | parsing-with-strptime | namedtuple | list | operator | tuple | string | identity-operators-(is,-is-not) | python-repl | using-lists-as-stacks | collections | string-method | math-copysign | polymorphism | turtle | conditional-statement | slicing | type-conversion | memory | list-indexing | data-structures | data-structure | indexing | lambda-function | identity-operator | using-os-and-pathlib-modules | python-history | dictionary | int | data_structure | id-function | set-operation | operator-or | while-loop | parameter | copy | higher-order-function | context-manager | magic-method | data-type | list-comprehension | data-types | datatype | built-in | immutable-data-type | package-management | expression | joining-and-merging-dataframes | deep-copy | statement | with-statement | introduction-to-python | writing:-write(),-writelines() ...