473,396 Members | 2,013 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.

Learning to think differently...

true911m
Here's one to chuckle at later...

I was playing around with the random number generator, and wondering how random it is, so I decided to test it.

Made a list of ten zeros. Seeded random, created a loop, and incremented list[random.randint(0,9)] each time.

Results were a little rough at 1000 and 10000, so I decided to try some bigger numbers (the more you flip a coin, the closer your results should approach 50%...).

Let's try 10**8.

Here's the good part. In typical BASIC-esque mentality, and remembering one of my Python books saying that 'for' is a little quicker than 'while', I used this:

Expand|Select|Wrap|Line Numbers
  1. for i in range(10**8):
  2.  
I waited a couple minutes, as I thought I'd need to, when Windows tells me it needs to expand my page file (hmm, I just installed that memory optimizer...), and the program failed with a MemoryError.

I was chasing my tail, watching the memory graph eat 250+ free MB each time I started the program, and eliminating sections of code to find the culprit. I finally tried 'while' with a counter, which ran and finished without a blip on the graph.

Of course, while you chuckle, I now realize it wasn't the 'for', but the list with 10**8 items in it that caused my problem. :)

Anyway, so this isn't completely wasted bandwidth, I think I recall reading about an alternate version of range() that delivers each item just-in-time, rather than altogether at the beginning, but I couldn't find it in the Python docs. Does anyone know what that function might be?

Thanks.
Dec 6 '06 #1
7 3137
bartonc
6,596 Expert 4TB
Yeah, range() is notorious. The docs say:

2.3.6.3 XRange Type
The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages.
XRange objects have very little behavior: they only support indexing, iteration, and the len() function.
Dec 6 '06 #2
xrange() ... that's it! I'll see how that stacks up.

I referred earlier to an assertion that 'for' is more efficient than 'while', and that makes sense perhaps for its intended purpose, which is iterating through a list.

But what are your thoughts on an application like this, where the actual need is a counter? It seems the glaring inefficiency in this case is not the for/while difference, but the creation of the list in the first place with 'for', rather than incrementing a counter as it is typically used in the BASICs.

Is there a more pythonic loop/count technique I might use besides either of these?
Dec 6 '06 #3
bvdet
2,851 Expert Mod 2GB
To repeat a number of times:
Expand|Select|Wrap|Line Numbers
  1. for i in xrange(num):
For a counter for use as an index to a list, I like to use:
Expand|Select|Wrap|Line Numbers
  1. for i in range(len(lst)):
. To step through a list, I like:
Expand|Select|Wrap|Line Numbers
  1. for i in list:
Sometimes you might need a counter as well as step through a list:
Expand|Select|Wrap|Line Numbers
  1. for i, str1 in enumerate(lst):
  2.     print i, str1
For what is 'pythonic' and what is not, I'll leave to the experts to decide!
Dec 6 '06 #4
I thought that using xrange might be a stubborn means of furthering the BASIC view of the problem, by sticking with the use of 'for' -- I thought that generating that list, even partially, would be a waste of (CPU) time.

However, xrange performed very well, with only slight overhead compared to the 'while' solution.

Averages for seven runs of 1 million iterations each:

for - range():
9.59 secs

for - xrange():
6.76 secs

while - i+=1
6.72 secs

Again, this is a situation where the counting is merely academic, and therefore range() must create the list for the sole purpose of performing the iteration. In situations where pre-existing lists of data are processed, 'for' should outperform 'while'.

Oh, and regarding that randint() test earlier, it seems quite random - variance was less than 0.005% from the "ideal" for a sample of 100 million generated numbers.
Dec 6 '06 #5
Oh, and thanks, bv.

Barton has responded to so many of my posts that I didn't realize you were someone else. :)
Dec 6 '06 #6
bvdet
2,851 Expert Mod 2GB
Oh, and thanks, bv.

Barton has responded to so many of my posts that I didn't realize you were someone else. :)
You are welcome! This is an interesting thread. Keep posting.
Dec 6 '06 #7
bartonc
6,596 Expert 4TB
You are welcome! This is an interesting thread. Keep posting.
Our community is growing and maturing! Keep at it guys!
Dec 7 '06 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Ryan Walker | last post by:
Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that...
1
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
25
by: Byte | last post by:
I know this is probably a stupid question, but I'm learning Python, and am trying to get the if function to work with letters/words. Basicly, I'm trying to write a script that when run, says ...
7
by: Max | last post by:
On monday I start a semester course in Python (the alternative was Java). I was looking through the course outline and noticed the following: 1) UserDict is used. This is deprecated, right? 2)...
26
by: mfasoccer | last post by:
I am sorry if this is an inappropriate place to put this post, if so please delete it. I am wondering about a few things. Do you guys recommend learning C as a second language, as someone who...
78
by: arnuld | last post by:
hai all, i am standing on a "crossroad to C++". I am here in front of you as i have a problem. i will be brief. Please do not think: "arnuld is sick", i am really struggling & doing hard-work to...
7
by: CribbsStyle | last post by:
Whats the best tool to write PHP Code? Also whats the best resource to learn PHP? Thanks Dennis
22
by: -Lost | last post by:
In a recent programming class I was taking, another student went on and on about how C was a dead language. I tried my best to explain why this was not so, but he was more able to explain things...
16
by: John Salerno | last post by:
Just something that crosses my mind every time I delve into "Learning Python" each night. Does anyone see any value in learning Python when you don't need to for school, work, or any other reason?...
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: 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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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.