Level 5 : What happens when the following code is executed?


class CustomIterator:
    def __init__(self, values):
        self.values = values
        self.index = len(values)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index -= 1
        return self.values[self.index]

it = CustomIterator(["A", "B", "C"])
print(list(it))
print(list(it))

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