BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Python - Iterators

python_logo




Bookmark and Share





bogotobogo.com site search:

Iterators

In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a collection regardless of its specific implementation.

  1. iterable produces iterator via __iter__()
  2. iterator = iterable.__iter__()  
    

  3. iterator produces a stream of values via next()
  4. value = iterator.next()  
    value = iterator.next()
    ...
    

To be more specific, we can start from an iterable, and we know a list (e.g, [1,2,3]) is iterable. iter(iterable) produces an iterater, and from this we can get stream of values.


iterable-vs-iterator.png
>>> # Python 3
>>> iterable = [1,2,3]
>>> iterator = iterable.__iter__()    # or iterator = iter(iterable)
>>> type(iterator)
<type 'listiterator'>
>>> value = iterator.__next__()   # or value = next(iterator)
>>> print(value)
1
>>> value = next(iterator)
>>> print(value)
2
>>>
>>> # Python 2
>>> iterable = [1,2,3]
>>> iterator = iterable.__iter__()
>>> type(iterator)
<type 'listiterator'>
>>> value = iterator.next()
>>> value
1
>>> value = next(iterator)
>>> value
2





Iterators in Python are a fundamental part of the language and in many cases go unseen as they are implicitly used in the for (foreach) statement, in list comprehensions, and in generator expressions.

"Iterators are the secret sauce of Python 3. They're everywhere, underlying everything, always just out of sight. Comprehensions are just a simple form of iterators. Generators are just a simple form of iterators. A function that yields values is a nice, compact way of building an iterator without building an iterator." - Mark Pilgrim

All of Python's standard built-in sequence types support iteration, as well as many classes which are part of the standard library.



The for loop can work on any sequence including lists, tuples, and strings:

>>> for x in [1, 2, 3, 4, 5]:
	print(x ** 3, end=' ')
	
1 8 27 64 125 
>>> 
>>> for x in (1, 2, 3, 4, 5):
	print(x ** 3, end=' ')
	
1 8 27 64 125 
>>> 
>>> for x in 'Beethoven':
	print(x * 3, end=' ')
	
BBB eee eee ttt hhh ooo vvv eee nnn 
>>> 

The for loop works on any iterable object. Actually, this is true of all iteration tools that scan objects from left to right in Python including for loops, the list comprehensions, and the map built-in function, etc.

Though the concept of iterable objects is relatively recent in Python, it has come to permeate the language's design. Actually, it is a generalization of the sequences. An object is iterable if it is either a physically stored sequence or an object that produces one result at a time in the context of an iteration tool like a for loop.

Note: For Python 2.x, the print is not a function but a statement. So, the right statement for the print is:

>>> for x in [1, 2, 3, 4, 5]:
...     print x ** 3,
... 
1 8 27 64 125


File Iterators

As a way of understanding the file iterator, we'll look at how it works with a file. Open file objects have readline() method. This reads one line each time we call readline(), we advance to the next line. At the end of the file, an empty string is returned. We detect it to get out of the loop.

>>> f = open('C:\\workspace\\Masters.txt')
>>> f.readline()
'Michelangelo Buonarroti \n'
>>> f.readline()
'Pablo Picasso\n'
>>> f.readline()
'Rembrandt van Rijn \n'
>>> f.readline()
'Leonardo Da Vinci \n'
>>> f.readline()
'Claude Monet \n'
>>> f.readline()
'\n'
# Returns an empty string at end-of-file
>>> f.readline()
''
>>> 

But files also have a __next__() method that has an identical effect. It returns the next line from a file each time it is called. The only difference is that __next__() method raises a built-in StopIteration exception at end-of-file instead of returning an empty string.

>>> f = open('C:\\workspace\\Masters.txt')
>>> f.__next__()
'Michelangelo Buonarroti \n'
>>> f.__next__()
'Pablo Picasso\n'
>>> f.__next__()
'Rembrandt van Rijn \n'
>>> f.__next__()
'Leonardo Da Vinci \n'
>>> f.__next__()
'Claude Monet \n'
>>> f.__next__()
'\n'
>>> f.__next__()
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    f.__next__()
StopIteration
>>> 

This interface is what we call the iteration protocol in Python. Any object with a __next__() method to advance to a next result is considered iterable. Any such object can also be stepped through with a for loop because all iteration tools work internally be calling __next__() method on each iteration.

So, the best way to read a text file line by line is not reading it at all. Instead let the for loop to call __next__() method to advance to the next line. The file object's iterator will do the work of loading lines as we go.

The example below prints each line without reading from the file at all:

>>> for line in open('C:\\workspace\\Masters.txt'):
	print(line.upper(), end=' ')

MICHELANGELO BUONARROTI 
 PABLO PICASSO
 REMBRANDT VAN RIJN 
 LEONARDO DA VINCI 
 CLAUDE MONET 

Here, we use end=' ' in print to suppress adding a \n because line strings already have one. This is considered the best way to read text files line by line today. The reasons are:

  1. It's the simplest to code.
  2. It might be the quickest to run.
  3. It is the best in terms of memory usage.

The older way is to call the file readlines() method to load the file's content into memory as a list of line strings:

>>> for line in open('C:\\workspace\\Masters.txt').readlines():
	print(line.upper(), end=' ')

	
MICHELANGELO BUONARROTI 
 PABLO PICASSO
 REMBRANDT VAN RIJN 
 LEONARDO DA VINCI 
 CLAUDE MONET 
 

This readlines() loads the entire file into memory all at once. So, it will not work for files too big to fit into the memory. On the contrary, the iterator-based version is immune to such memory-explosion issues and it might run quicker, too.



iter and next

We have a built-in next() function for manual iteration. The next() function automatically calls an object's __next__() method. For an object X, the call next(X) is the same as X.__next__() but simpler.

>>> f = open('C:\\workspace\\Masters.txt')
>>> f.__next__()
'Michelangelo Buonarroti \n'
>>> f.__next__()
'Pablo Picasso\n'
>>> 
>>> f = open('C:\\workspace\\Masters.txt')
>>> next(f)
'Michelangelo Buonarroti \n'
>>> next(f)
'Pablo Picasso\n'
>>> 

When the for loop begins, it obtains an iterator from the iterable object by passing it to the iter built-in function. This object returned by iter has the required the __next__() method. Let's look at the internals of this through for loop with lists. For Python versions < 3, we may want to use next(iterObj) instead of iterobj.__next__().

>>> # works only for v.3+

>>> L = [1, 2, 3]

>>> iter(L) is L     # L itself is not an iterator object
False

>>> iterObj = iter(L)
>>> iterObj.__next__ ()
1
>>> iterObj.__next__ ()
2
>>> iterObj.__next__ ()
3
>>> iterObj.__next__ ()
Traceback (most recent call last):
  File .....
    iterObj.__next__ ()
StopIteration
>>> 

The step:

 
iterObj = iter(L)

is not required for files because a file object is its own iterator. In other words, files have their own __next__() method. So, for file object, we do not need to get a returned iterator.

>>> f = open('C:\\workspace\\Masters.txt')
>>> iter(f) is f
True
>>> f.__next__ ()
'Michelangelo Buonarroti \n'
>>> 

But list and other built-in object are not their own iterators because they support multiple open iterations. For an object like that, we must call iter to start iteration:

>>> L = [1, 2, 3]
>>> iter(L) is L
False
>>> L.__next__()
Traceback (most recent call last):
  File ...
    L.__next__()
AttributeError: 'list' object has no attribute '__next__'
>>> 
>>>
>>> iterObj = iter(L)
>>> iterObj.__next__()
1
>>> next(iterObj)
2
>>> 

Though Python iteration tools call these functions automatically, we can use them to apply the iteration protocol manually, too.

>>> L = [1, 2, 3]
>>> 
>>> for x in L:  		# Automatic iteration
	print(x ** 3, end=' ') 	# Obtains iter, calls __next__
				# and catches exceptions

					
1 8 27 
>>> iterObj = iter(L)		# Manual iteration which is
>>> 				# for loops usually do					




Other Iterators

We've looked at the iterators for files and lists. How about the others such as dictionaries?

To step through the keys of a dictionary is to request its keys list explicitly:

>>> D = {'a':97, 'b':98, 'c':99}
>>> for k in D.keys():
	print(k, D[k])

	
a 97
c 99
b 98

Dictionaries have an iterator that automatically returns one key at a time in an iteration context:

>>> iterObj = iter(D)
>>> next(iterObj)
'a'
>>> next(iterObj)
'c'
>>> next(iterObj)
'b'
>>> next(iterObj)
Traceback (most recent call last):
  File ...
    next(iterObj)
StopIteration
>>> 

So, we no longer need to call the keys() method to step through dictionary keys. The for loop will use the iteration protocol to grab one key at a time through:

>>> for k in D:
	print(k, D[k])

	
a 97
c 99
b 98

Other Python object types also support the iterator protocol and thus may be used in for loops too. For example, shelves which is an access-by-key file system for Python objects and the results from os.popen which is a tool for reading the output of shell commands are iterable as well:

>>> import os
>>> P = os.popen('dir')
>>> P.__next__()
' Volume in drive C has no label.\n'
>>> P.__next__()
' Volume Serial Number is 0C60-AED5\n'
>>> next(P)
Traceback (most recent call last):
  File ...
    next(P)
TypeError: _wrap_close object is not an iterator
>>> 

Note that popen object support a P.next() method, they support the P.__next__() method, but not the next(P) built-in.


The iteration protocol also is the reason that we've had to wrap some results in a list call to see their values all at once (Python ver. 3.x). Object that are iterable returns results one at a time, not in a physical list:

>>> R = range(5)
>>> # Ranges are iterables in 3.0
>>> R
range(0, 5)
>>> # Use iteration protocol to produce results
>>> iterObj = iter(R)
>>> next(iterObj)
0
>>> next(iterObj)
1
>>> # Use list to collect all results at once
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> 

Note on range():
For Python 3.x, range just returns an iterator, and generates items in the range on demand instead of building the list results in memory (Python 2.x does this). So, if we want to display result, we must use list(range(...)):

>>> L = range(5)

>>> L
range(0, 5)       # Python 3.x
>>> list(L)
[0, 1, 2, 3, 4]

>>> L
[0, 1, 2, 3, 4]   # Python 2.x

Now we should be able to see how it explains why the enumerate tool works the way it does:

>>> E = enumerate('Python')
>>> E
<enumerate object at 0x0000000003234678>
>>> iterObj = iter(E)
>>> # Generate results with iteration protocol
>>> next(iterObj)
(0, 'P')
>>> next(iterObj)
(1, 'y')
>>> list(enumerate('Python'))
[(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]








Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master