search
HomeBackend DevelopmentPython TutorialExplaining Iterable vs Iterator in Python

Explaining Iterable vs Iterator in Python

The aim of this page?is to demonstrate the dynamics of the 2 iteration protocols:

  1. iterable
  2. iterator

1. BUT FIRST (TO ADD TO CONFUSINGLY SIMILAR WORDS), LET'S ADDRESS ITERATION

  • iteration - of course - is taking items one by one from a source and doing something with each in turn
  • in python, this is commonly used in
    • a) for/while loops and
    • b) comprehensions
  • by default - these structures iterate over the whole structure
  • sometimes, however, a more fine-grained control could be needed - like in generators
  • for this, there are 2 important concepts/protocols, on top of which much of Python is constructed:
  • a) iterable objects
  • b) iterator objects
  • both are reflected in standard python protocols
  • this is not something extra: actually, for/while loops and comprehensions are built directly upon these lower-level elements of iteration protocols

2. ITER() METHOD CREATES AN ITERATOR FROM AN ITERABLE

  • iterable object (collection or stream of objects) is any object that can be passed into the built-in iter() function
  • once passed the built-in iter() function and which returns an iterator object of a passed type, i.e. a string iterator is created with
>>> example_iterator = iter('abc')
>>> example_iterator
<str_iterator object at>
</str_iterator>
  • note that iterator is an implicit sequence object providing sequential (not random!) access to an underlying sequential dataset
  • for example range object itself is not an iterator
  • iterator does not allow the access to arbitrary element of the underlying series
  • they provide access only to the next element of the series
  • they provide sequential access
<!-- THIS IS NOT AN ITERATOR -->
>>> r = range(10)[5]
>>> r
5

3. NEXT() FUNCTION RETURNS THE NEXT VALUE FROM AN ITERATOR

  • the built-in next() requires an iterator object - and it returns the next value in the iteration of a collection
  • iterator consists of 2 components:
  • mechanism for retrieving the next element of a collection
  • mechanism for signalling the end of the series

In programming languages with built-in object systems, this abstraction typically corresponds to a particular interface that can be implemented by classes

  • next() allows to consider each item in turn / on request - not the whole series from beginning to an end
  • there are 2 messages iterator interface includes
    • next → query for the next element
    • iter → return the iterator
  • constraint: iterator can be iterated over once

4. CLASSROOM EXAMPLE - FROM ITERABLE TO ITERATOR TO STOPITERATION EXCEPTION

  • Python, liberally, raises an exception of the type StopIteration
>>> example_iterator = iter('abc')
>>> example_iterator
<str_iterator object at>
</str_iterator>

5. REAL-LIFE EXAMPLE - UNIT TESTING MULTIPLE COMMAND LINE INPUTS

  1. define/get an iterable object such as a list ["20.01", "y"]
  2. pass an iterable object into iter() → create an iterator object
  3. pass an iterator object into a next() to yield the next value of the list each time the input function is called in the code
<!-- THIS IS NOT AN ITERATOR -->
>>> r = range(10)[5]
>>> r
5
  • the first time input() is encountered, the "20.01" value is passed,
  • the second time it is "y"
  • the third time it would be an exception

6. LINKS

  • https://mypy.readthedocs.io/en/stable/protocols.html#iteration-protocols
  • 5.2 Implicit Sequences - SICP in Python

The above is the detailed content of Explaining Iterable vs Iterator in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools