interating over single element array

Terry Reedy tjreedy at
Sat Jun 9 09:48:12 CEST 2007

"Basilisk96" <basilisk96 at> wrote in message 
news:1181345593.788652.275380 at
| On Jun 8, 11:54 am, "T. Crane" <tcr... at> wrote:
| You can also do this (if tuples are okay in your case):
| a = 1,
| The comma turns 'a' into a tuple (1,) which is both iterable and has a
| length of 1.
| I have run into this issue before with a function that took a list of
| filenames (strings), and needed to iterate over the list to operate on
| the input files. For the case when the input would be a single file, I
| needed to turn the input string into an iterable such that the 'for'
| loop would not iterate on the filename characters (a rather
| undesirable gotcha, you understand :-) ). So I solved my problem like
| this:
|  def loadfiles(filelist):
|    if not isinstance(filelist, list):
|      filelist = filelist,

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 

|    for filename in filelist:
|      f = open(filename,'r')
|      #do interesting stuff with file, etc...
| ..and it's been working very well.
| Cheers,
| -Basilisk96
| -- 

More information about the Python-list mailing list