473,396 Members | 2,158 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,396 software developers and data experts.

Counting iterations

Is there a better way to count iterations that this?:

pets = 0
for i in pets:
pets += 1
print "pet" + "#" + pets

Thanks,
Derek Basch

Jul 18 '05 #1
11 7289
Derek Basch wrote:
Is there a better way to count iterations that this?:

pets = 0
for i in pets:
pets += 1
print "pet" + "#" + pets


for i, pet in enumerate(pets):
print 'pet#%i' % (i + 1)

STeVe
Jul 18 '05 #2
Derek Basch wrote:
Is there a better way to count iterations that this?:

pets = 0
for i in pets:
pets += 1
print "pet" + "#" + pets


You can use 'enumerate' to get the index, but the code above wont work -
you are trying to iterate over a non-sequence.

Will McGugan

--
"".join( [ {'@':'@','.':'.'}.get(c,None) or chr(97+((ord(c)-97)+13)%26)
for c in "jv**@jvyyzpthtna.pbz" ] )
Jul 18 '05 #3
ooops you are right. Should have been:

pets = ["cat", "dog", "bird"]
num_pets = 0
for i in pets:
num_pets += 1
print "pet" + "#" + num_pets

That's the problem with one offs. I don't read them :).

Jul 18 '05 #4
Derek Basch wrote:
ooops you are right. Should have been:

pets = ["cat", "dog", "bird"]
num_pets = 0
for i in pets:
num_pets += 1
print "pet" + "#" + num_pets


Traceback (most recent call last):
File "example.py", line 5, in ?
print "pet" + "#" + num_pets
TypeError: cannot concatenate 'str' and 'int' objects

</F>

Jul 18 '05 #5
You should avoid the "a" + "b" + "c" -kind of concatenation. As strings
at immutable in Python you actually makes copies all the time and it's
slow!

The alternative used in Steven Bethard's example is preferable.

Jul 18 '05 #6
runes wrote:
You should avoid the "a" + "b" + "c" -kind of concatenation. As strings
at immutable in Python you actually makes copies all the time and it's
slow!


The OP wrote

print "pet" + "#" + num_pets

(properly str(num_pets) )

You recommended the "alternative used in Steven Bethard's example"

print 'pet#%i' % (i + 1)

because "it's slow". I disagree, it isn't for this code.
It's comparable in performance to interpolation and most
of the time is spent in converting int -> string. Indeed
if the object to be merged is a string then the addition
version is faster than interpolation.

Here's the details.

The string concatenation performance that you're
talking about doesn't hit until there are multiple
appends to the same string, where "multiple" is rather
more than 2. The advice usually applies to things like

text = ""
for line in open(filename, "U"):
text += line

which is much slower than, say
lines = []
for line in open(filename, "U")
lines.append(line)
text = "".join(lines)

or the more modern
text = "".join(open(filename, "U"))

to say nothing of
text = open(filename, "U").read() :)

Anyway, to get back to the example at hand,
consider what happens in

"pet#%i" % (i+1)

(NOTE: most times that's written %d instead of %i)

The run-time needs to parse the format string
and construct a new string from the components.
Internally it does the same thing as

"pet#" + str(i+1)

except that it's done at the C level instead
Python and the implementation overallocates
100 bytes so there isn't an extra allocation
in cases like this.

Personally I would expect the "%" code to be
about the same performance as the "+" code.
Of course the real test is in the timing.
Here's what I tried. NOTE: I reformatted by
hand to make it more readable. Line breaks and
the \ continuation character may have introduced
bugs.

First, the original code along with the 'str()'
correction.

% python /usr/local/lib/python2.3/timeit.py -s \
'pets = ["cat", "dog", "bird"]' \
'num_pets=0' 'for pet in pets:' \
' num_pets += 1' \
' s="pet" + "#" + str(num_pets)'
100000 loops, best of 3:
14.5 usec per loop
There's no need for the "pet" + "#" so I'll
turn that into "pet#"

% python /usr/local/lib/python2.3/timeit.py -s \
'pets = ["cat", "dog", "bird"]' \
'num_pets=0' \
'for pet in pets:' \
' num_pets += 1' \
' s="pet#" + str(num_pets)'
100000 loops, best of 3: 12.8 usec per loop

That's 1.3 extra usecs.

By comparison here's the "%" version.

% python /usr/local/lib/python2.3/timeit.py -s \
'pets = ["cat", "dog", "bird"]'\
'num_pets=0' \
'for pet in pets:' \
' num_pets += 1' \
' s="pet#%s" % num_pets'
100000 loops, best of 3: 10.8 usec per loop

I'm surprised that it's that much faster - a
good 2 microseconds and that isn't the only
code in that loop.

But both the "%" and "+" solutions need to
convert the number into a string. If I
use an existing string I find

% python /usr/local/lib/python2.3/timeit.py -s \
'pets = ["cat", "dog", "bird"]' \
'num_pets=0' \
'for pet in pets:' \
' num_pets += 1' \
' s="pet#" + pet'
100000 loops, best of 3: 4.62 usec per loop

So really most of the time - about 8 usec - is
spent in converting int -> string and the
hit for string concatenation or interpolation
isn't as big a problem.

Compare with the string interpolation form
of the last version

% python /usr/local/lib/python2.3/timeit.py -s \
'pets = ["cat", "dog", "bird"]' \
'num_pets=0' 'for pet in pets:' \
' num_pets += 1' \
' s="pet#%s" % pet' \
100000 loops, best of 3: 7.55 usec per loop
In this case you can see that the % version is
slower (by 2usec) than the + version.

I therefore disagree with the idea that simple
string concatenation is always to be eschewed
over string interpolation.

Andrew
da***@dalkescientific.com

Jul 18 '05 #7
Andrew Dalke wrote:
"pet#%i" % (i+1)

(NOTE: most times that's written %d instead of %i)


Any reason to prefer %d over %i? The library reference seems to suggest
that they're the same thing[1]. I've typically used %i since I can
remember it from the int type, like I can remember %f from the float
type. Is there any reason not to?

STeVe

[1] http://docs.python.org/lib/typesseq-strings.html
Jul 18 '05 #8

[Andrew Dalke]
I therefore disagree with the idea that simple
string concatenation is always to be eschewed
over string interpolation.


Andrew, what you write makes sense. I've never really tested it, just
read it several places, fx here:
http://www.python.org/moin/PythonSpe...Tips#stringcat

Jul 18 '05 #9
Interesting stuff Andrew. I do generally avoid string concantination
for the reason listed in the Python Performance Tips but your analysis
kinda puts that in question. Such a dense discussion for me just trying
to find the enumerate() function :). I guess that is why the python
list is so great. You guys always rip my code apart and correct my
style. Even if it is just a stupid one off example.

Thanks everyone,
Derek Basch

Jul 18 '05 #10

"runes" <ru*********@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...

[Andrew Dalke]
I therefore disagree with the idea that simple
string concatenation is always to be eschewed
over string interpolation.

String cat (+) is fine for joining a few short strings.
Andrew, what you write makes sense. I've never really tested it, just
read it several places, fx here:
http://www.python.org/moin/PythonSpe...Tips#stringcat


This is about making long strings in situations where performance is an
issue.

Terry J. Reedy

Jul 18 '05 #11
Derek Basch wrote:
Interesting stuff Andrew. I do generally avoid string concantination
for the reason listed in the Python Performance Tips but your analysis
kinda puts that in question.


Thanks.

It was interesting for me to. I hadn't looked at the implementation
for string % before and was rather surprised to find that it
overallocates 100 bytes to reduce the number of allocs done. It's
simpler than the implementation I considered.

Andrew
da***@dalkescientific.com

Jul 18 '05 #12

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

Similar topics

6
by: Elbert Lev | last post by:
Please correct me if I'm wrong. Python (as I understand) uses reference counting to determine when to delete the object. As soon as the object goes out of the scope it is deleted. Python does...
7
by: sathyashrayan | last post by:
Group, Following function will check weather a bit is set in the given variouble x. int bit_count(long x) { int n = 0; /* ** The loop will execute once for each bit of x set,
3
by: GJ | last post by:
I came accross the following code snippet to count the number of 1 bit in a word (32bit in this case). However I am not able to understand it thoroughly.. Could anyone please explain this. ...
1
by: j | last post by:
Hi, I've been trying to do line/character counts on documents that are being uploaded. As well as the "counting" I also have to remove certain sections from the file. So, firstly I was working...
4
by: aaronfude | last post by:
Hi, Please consider the following class (it's not really my class, but it's a good example for my question): class Vector { int myN; double *myX; Vector(int n) : myN(n), myX(new double) { }...
18
by: Derek Basch | last post by:
What is the best way to count nested loop iterations? I can only figure to use an index but that seems kludgy. index = 0 for animal in zoo: for color in animal: index += 1 Thanks, Derek...
6
by: MLH | last post by:
If you're only furnished the table name of a table in your database, what can I do in VBA to count tablle records in a given table? Seeking simplest method. In other words, I don't have the...
6
by: Matt Chwastek | last post by:
Anyone who can help, I am curretnly attempting to write some code that will allow iteration using a vector<intfrom the highest possilbe degree of a combination of ones & zeros (111, 110, 101,...
5
by: sololoquist | last post by:
#define COUNT_UP #include <stdio.h> #define N 10 int main() { int i; #ifdef COUNT_UP for (i = 0; i < N; i++)
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.