interating over single element array
Basilisk96
basilisk96 at gmail.com
Fri Jun 8 19:33:13 EDT 2007
On Jun 8, 11:54 am, "T. Crane" <tcr... at REMOVETHISuiuc.edu> wrote:
> >> any suggestions are appreciated,
>
> > Yes, don't try iterating over objects that are not iterable. ;-)
>
> Ah, yes... I hadn't thought of that :)
>
> thanks,
> trevis
>
>
>
> > What you *can* do is iterating over lists, tuples or other iterables with
> > just one element in them. Try ``a = [1]``.
>
> > Ciao,
> > Marc 'BlackJack' Rintsch
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,
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