Level 9 : What happens when we run the following code?


class ReverseIterator:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

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

rev = ReverseIterator("Python")
print("".join(rev))

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