• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Iterable and Iterator

Iterable and Iterator

In any programming language especially python, Iteration simply means to access each item of something one after another generally using a loop. For instance, a list of car names can be printed out one by one using a for loop, like this:

# list of cars
cars = ['Hyundai', 'BMW', 'Jaguar', 'Kia', 'MG']

for car in cars:
  print("Name of car: ", car)

Output:

Name of car:  Hyundai
Name of car:  BMW
Name of car:  Jaguar
Name of car:  Kia
Name of car:  MG

The process shown above was iteration which involved accessing all the items of the list one by one.

 

What is an Iterable?

An iterable in python programming is referred to as anything that can be looped through or can be iterated over.

For instance, lists, tuples, dictionaries, etc. all are iterable. In simpler words, anything that can appear on the right side of a for-loop: for x in iterable: … is iterable.

One important property of an iterable is that it has an __iter__() method or iter() method and this method specifically allows any iterable to return an iterator object.

Internally the iter() method makes a call to the __iter__() method and returns an iterator object.

 

What is an Iterator?

An iterator is an object which can be looped through and it maintains its state during the iteration by remembering where it is during an iteration i.e. It has the last memory.

An Iterator in python programming has a __next__() method that returns the next value in the iteration and updates the state to point at the next value.

Iterators also have a method that returns a self-object known as the __iter__ method.

 

Getting an Iterator object from Iterable

Iterator object can easily be gotten either by passing a predefined or pre-created iterable to the iter() method or by using the __iter__() method on that iterable.

Check out this example: 

# list of cars
cars = ['Audi', 'BMW', 'Jaguar', 'Kia', 'MG', 'Skoda']

# get iterator object using the iter() method
cars_iter = iter(cars)

# use the next method to iterate through the list
print(next(cars_iter))

# let's do it once more
print(next(cars_iter))

# want to see how to use __next__()
print(cars_iter.__next__())

# one more time
print(cars_iter.__next__())

# lets finish the list
print(cars_iter.__next__())
# this will print Skoda which is the last element
print(cars_iter.__next__())

# this will give error
print(cars_iter.__next__())

Output:

Audi
BMW
Jaguar
Kia
MG
Skoda

Traceback (most recent call last):
  File "/tmp/sessions/52ed47aa5f103wwe/main.py", line 25, in <module>
    print(cars_iter.__next__())
StopIteration

 

In the above example, the iter() method was used, well the __iter__() method can also be used like this:

# we can use __iter__() method too
cars_iter_new = cars.__iter__()

# print the data
print(cars_iter_new.__next__())

Depicting from the example above, the state of the corresponding iterator is incremented and the value that is next to the previous value is returned through the next() or the __next__() method.

Also, there is an exception in the output that won't be unnoticed and the exception is the StopIteration exception which occurs when there are no values left in an iterator to iterate i.e. after the list has ended and to call the next() or __next__() method is called.

 

Is this how for Loop works internally?

Python provides loops like the for loop which internally performs all the steps mentioned above. It minimizes the stress involved in getting the iterator object and then calling the next function again and again.

So whenever a for loop is used like the below sample:

# list of cars
cars = ['Audi', 'BMW', 'Jaguar', 'Kia', 'MG', 'Skoda']

for car in cars:
  print("Name of car: ", car)

The for loop does this internally:

# iterator object is created
iter_obj = iter(cars)

while True:
	try:
		element = next(iter_obj)
		# perform some operation like print the value
	except StopIteration:
	    # break out of loop when the list ends 
		break

In python programming, for loop is created to aid the iteration of iterable items using the iterator object as it works internally.

 

Making a class Iterable by creating custom Iterator

Creating our iterators is not a herculean task as it involves implementing __iter__() and __next__() methods.

An object of the iterator which in our case will be the object of the class itself will be returned when the __iter__() method is used.

And the next element will be returned every time the __next__() method is called thereby raising the StopIteration exception upon reaching the end.

Below is a simple class Counting which will print the counting starting from 1 till the number provided while the class is initiated.

class Counting:
    def __init__(self, limit):
        self.limit = limit
    
    # implementing the __iter__ method
    def __iter__(self):
        self.current = 0
        return self
    
    # implementing the __next__ method
    def __next__(self): 
        if self.current < self.limit:
            self.current += 1
            return self.current
        else:
            raise StopIteration
            
if __name__=='__main__':
  # create object of Counting class
  counting = Counting(10)
  
  # use for loop on it
  for x in counting:
    print(x)

Output:

1
2
3
4
5
6
7
8
9
10

Lastly, the iter() method can also be called on the object of the Counting class then employ the next() method on the iterator to print the values one by one.

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.