interating over single element array

Marc 'BlackJack' Rintsch bj_666 at
Sat Jun 9 14:55:42 CEST 2007

In <1181391368.112303.284890 at>, Basilisk96

> "Terry Reedy" <tjre... at> wrote:
>> Any what if 'filelist' is any iterable other than a string or list?  Your
>> code is broken, and unnecessarily so.  So I would call the parameter
>> 'files' and test for isinstance(files, str) #or basestring.  And wrap if it
>> is.
> Can you give an example of such an iterable (other than a tuple)? I'd
> certainly like to fix my 'fix' to work for a more general case.

def iter_filenames(filename):
    lines = open(filename, 'r')
    for line in lines:
        yield line.rstrip()

filenames = iter_filenames('files.txt')

Now `filenames` is an iterable over strings representing file names but
it's not a `list`.  And it's easy to come up with iterables over strings
that produce the data themselves, for example by attaching a counter to a
basename, or extracting the names from XML files, fetching them from a
database etc.

	Marc 'BlackJack' Rintsch

More information about the Python-list mailing list