473,378 Members | 1,119 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

interating over single element array

Hi all,

Can someone please explain to me why I can't do something like this:

a = 1

for value in a:
print str(value)

If I run this I get the error:

'int' object is not iterable

Obivously this is an absurd example that I would never do, but in my
application the length of 'a' can be anything greater than 0, and I want to
be able to handle cases when 'a' has only one element without coding a
special case just in the event that len(a) = 1.

any suggestions are appreciated,
trevis
Jun 8 '07 #1
8 1362
In <4B******************@newssvr21.news.prodigy.net >, T. Crane wrote:
Can someone please explain to me why I can't do something like this:

a = 1

for value in a:
print str(value)

If I run this I get the error:

'int' object is not iterable
Well the message explains why you can't do this. `a` is bound to an
integer and integers are not iterable.
Obivously this is an absurd example that I would never do, but in my
application the length of 'a' can be anything greater than 0, and I want to
be able to handle cases when 'a' has only one element without coding a
special case just in the event that len(a) = 1.
``len(a)`` wouldn't work either because integers have no "length":

In [16]: a = 1

In [17]: len(a)
---------------------------------------------------------------------------
exceptions.TypeError Traceback (most recent call last)

/home/new/<ipython console>

TypeError: len() of unsized object
any suggestions are appreciated,
Yes, don't try iterating over objects that are not iterable. ;-)

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
Jun 8 '07 #2
>
>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

Jun 8 '07 #3
On Jun 8, 11:54 am, "T. Crane" <tcr...@REMOVETHISuiuc.eduwrote:
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

Jun 8 '07 #4

"Basilisk96" <ba********@gmail.comwrote in message
news:11**********************@h2g2000hsg.googlegro ups.com...
| On Jun 8, 11:54 am, "T. Crane" <tcr...@REMOVETHISuiuc.eduwrote:
| 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
is.

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

Jun 9 '07 #5
"Terry Reedy" <tjre...@udel.eduwrote:
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.

Regards,
-Basilisk96

Jun 9 '07 #6
In <11**********************@q75g2000hsh.googlegroups .com>, Basilisk96
wrote:
"Terry Reedy" <tjre...@udel.eduwrote:
>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()
lines.close()

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.

Ciao,
Marc 'BlackJack' Rintsch
Jun 9 '07 #7

"Basilisk96" <ba********@gmail.comwrote in message
news:11**********************@q75g2000hsh.googlegr oups.com...
| "Terry Reedy" <tjre...@udel.eduwrote:
| 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)?

Tuple was the first thing I thought of, and one will break the list test.
The next would be an iterator that walks a file hierarchy spitting out the
names of non-directory files, or all files with a certain extension, or all
files with a certain owner, or timestamp characteristic.

| I'd certainly like to fix my 'fix' to work for a more general case.

As I said, I think it as simple as changing 'not list' to 'is string'.

tjr


Jun 9 '07 #8
Thank you both for clearing that up.
-Basilisk96

Jun 9 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: richbl | last post by:
Hello all, I have a question about unserializing a single array element from a serialized array. Can this be done, or must I first unserialize the array, and then access the element? For...
19
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at...
14
by: maverick | last post by:
hi, i came across a code that had the following declaration : " int tlr_val; " If i am right the above declares an integer array trl_val having one element. It could as well be written as...
10
by: free2cric | last post by:
Hi, I have a single link list which is sorted. structure of which is like typedef struct mylist { int num; struct mylist *next;
6
by: Ole Nielsby | last post by:
I'm having a strange problem with sealing virtual indexers. Looks like a compiler error to me - or have I overlooked some obscure statement in the specs? I have two virtual indexers in the...
4
by: mab464 | last post by:
I have this code on my WAMP server running on my XP machine if ( isset( $_POST ) ) { for($i=0; $i<count($_POST);$i++) { if ($ans != NULL ) $ans .= ", " . $_POST ; // Not the first...
12
by: lorlarz | last post by:
In the code sample below, how are arguments a legitimate argument to Array.slice? Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object =...
33
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d...
4
by: arnuld | last post by:
I am passing an array of struct to a function to print its value. First I am getting Segfaults and weired values. 2nd, is there any elegant way to do this ? /* Learning how to use an array...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.