Reversing an iterator with older version of Python

A

Aki Niimura

Hello everyone,

I need to reverse an iterator in my program.

There are many posting to related to this. But most of them are
talking about how to expand the language to support such. In fact
reversed() built-in function is added in Python 2.4 to do such.

However, I need to use Python 2.2.x because of a module I'm using.

I can think of very crude way to reverse the iterator. But I don't
like it.
(It is so crude such that I'm ashamed to show it here)

Is there any elegant way to reverse an iterator using the features
available in older Python, such as Python 2.2.

These day, things are moving too fast to follow.

Any suggestions are highly appreciated.

Best regards,
Aki Niimura
 
A

A.M. Kuchling

I need to reverse an iterator in my program.

Convert it to a list and then reverse the list:

L = list(iterator)
L.reverse()

This means that the contents must fit in memory, but that's probably OK; if
you want to read the lines of a 2-gigabyte file in reverse order, you're
better off writing some custom code for reading the file.

--amk
 
A

Aki Niimura

A.M. Kuchling said:
Convert it to a list and then reverse the list:

L = list(iterator)
L.reverse()

It did the job for me.
Now my python program is working as I intended.
Hope I can move to a newer version of Python soon so that I can use
an iterator much like a list.

Thank you!
Aki Niimura
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top