Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I iterate over one iterator and then another?

I'd like to iterate two different iterators, something like this:

file1 = open('file1', 'r') file2 = open('file2', 'r') for item in one_then_another(file1, file2):     print item 

Which I'd expect to print all the lines of file1, then all the lines of file2.

I'd like something generic, as the iterators might not be files, this is just an example. I know I could do this with:

for item in [file1]+[file2]: 

but this reads both files into memory, which I'd prefer to avoid.

like image 697
xorsyst Avatar asked Feb 17 '14 10:02

xorsyst


People also ask

How do I use two iterators in Python?

Use the izip() Function to Iterate Over Two Lists in Python It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.

How do I iterate two different lengths of simultaneously in Python?

You can process adjacent items from the lists by using itertools. zip_longest() ( itertools. izip_longest() if using Python 2) to produce a sequence of paired items. Pairs will be padded with None for lists of mismatched length.

What are the two types of iteration in Python?

There are two types of iteration: Definite iteration, in which the number of repetitions is specified explicitly in advance. Indefinite iteration, in which the code block executes until some condition is met.


1 Answers

Use itertools.chain:

from itertools import chain for line in chain(file1, file2):    pass 

fileinput module also provides a similar feature:

import fileinput for line in fileinput.input(['file1', 'file2']):    pass 
like image 121
Ashwini Chaudhary Avatar answered Oct 08 '22 21:10

Ashwini Chaudhary