473,396 Members | 1,671 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.

Alternative to standard C "for"

Hi there,

I am quite new to Python, and have a straight & simple question.
In C, there is for (init; cond; advance). We all know that.
In Python there are two ways to loop over i=A..B (numerical.):
1) i = A
while i<B:
...do something...
i+=STEP
2) for i in range(A, B, STEP):
...do something...

First case looks quite nasty, because it's for more complicated
things, not numerical loops. Second is very nice, but with there's
problem. If i do ..in range(1, 100000000).. (what I really need
sometimes), it takes few hundred megs of memory and slows
down. Are there other good ways for this simple problem? Generators?

Adomas

Jul 18 '05 #1
15 1525
ad******************@gmail.com writes:
problem. If i do ..in range(1, 100000000).. (what I really need
sometimes), it takes few hundred megs of memory and slows
down. Are there other good ways for this simple problem? Generators?


use xrange instead of range.
Jul 18 '05 #2
> I am quite new to Python, and have a straight & simple question.
In C, there is for (init; cond; advance). We all know that.
In Python there are two ways to loop over i=A..B (numerical.):
1) i = A
while i<B:
...do something...
i+=STEP


This is indeed quite ugly. You rarely need such loops in Python and
with some thinking you can often translate the C-equivalent to
something more pythonic. As you guessed, your second problem is best
solved with a generator function - xrange(). It is completely equal to
range() except that it returns a generator instead of a list.
--
mvh Björn
Jul 18 '05 #3
ad******************@gmail.com wrote:
Are there other good ways for this simple problem? Generators?


Very interesting problem :) That never occured to me.

To prevent python from loading that entire list into memory, one
could, as you suggested, use a generator:
def genrange( start , stop , step = 1 ): while start < stop:
yield start
start += step
for x in range( 5 ): print "%s " % str( x ),

0 1 2 3 4
for x in genrange( 0 , 5 ):

print "%s " % str( x ),

0 1 2 3 4

--
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
Jul 18 '05 #4
Paul Rubin wrote:
use xrange instead of range.


Woops ;) I wasn't aware such a function existed.

apologies-for-reinventing-the-wheel-ly y'rs,
--
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
Jul 18 '05 #5
BJörn Lindqvist wrote:
I am quite new to Python, and have a straight & simple question.
In C, there is for (init; cond; advance). We all know that.
In Python there are two ways to loop over i=A..B (numerical.):
1) i = A
while i<B:
...do something...
i+=STEP


This is indeed quite ugly. You rarely need such loops in Python and
with some thinking you can often translate the C-equivalent to
something more pythonic. As you guessed, your second problem is best
solved with a generator function - xrange(). It is completely equal to
range() except that it returns a generator instead of a list.


Slight terminology glitch -- it does return an iterator, not a
generator. Generators are functions that return iterators.

regards,
Georg
Jul 18 '05 #6
> First case looks quite nasty, because it's for more complicated
things, not numerical loops. Second is very nice, but with there's
problem. If i do ..in range(1, 100000000).. (what I really need
sometimes), it takes few hundred megs of memory and slows
down. Are there other good ways for this simple problem? Generators?


Use xrange(). It computes the values as they are needed - not an entire
list.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #7
Georg Brandl <g.**************@gmx.net> wrote:
Slight terminology glitch -- it does return an iterator, not a
generator. Generators are functions that return iterators.


xrange returns an ITERABLE, not an ITERATOR. Videat:
a = xrange(23, 43)
a.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'


No next method -> not an iterator. iter(xrange(...)) DOES return an
iterator, btw.
Alex
Jul 18 '05 #8
Alex Martelli wrote:
Georg Brandl <g.**************@gmx.net> wrote:
Slight terminology glitch -- it does return an iterator, not a
generator. Generators are functions that return iterators.


xrange returns an ITERABLE, not an ITERATOR. Videat:
a = xrange(23, 43)
a.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'


No next method -> not an iterator. iter(xrange(...)) DOES return an
iterator, btw.


*wince*

This was SO clear...

Georg
Jul 18 '05 #9
Alex Martelli wrote:
Georg Brandl <g.**************@gmx.net> wrote:
Slight terminology glitch -- it does return an iterator, not a
generator. Generators are functions that return iterators.


xrange returns an ITERABLE, not an ITERATOR. Videat:
a = xrange(23, 43)
a.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'


No next method -> not an iterator. iter(xrange(...)) DOES return an
iterator, btw.


Thanks! Somehow it's always these little corrections that contain errors.

And, considering your other posts today, I got away quite well...

Georg
Jul 18 '05 #10
ad******************@gmail.com wrote:
Hi there,

I am quite new to Python, and have a straight & simple question.
In C, there is for (init; cond; advance). We all know that.
In Python there are two ways to loop over i=A..B (numerical.):
1) i = A
while i<B:
...do something...
i+=STEP
2) for i in range(A, B, STEP):
...do something...

First case looks quite nasty, because it's for more complicated
things, not numerical loops. Second is very nice, but with there's
problem. If i do ..in range(1, 100000000).. (what I really need
sometimes), it takes few hundred megs of memory and slows
down. Are there other good ways for this simple problem? Generators?

Adomas

This question is so important to you you had to post it twelve times? :-)

Look at "xrange", which is similar to range but doesn't create the whole
list.

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #11
On Sat, 2005-02-05 at 10:49, BJörn Lindqvist wrote:
I am quite new to Python, and have a straight & simple question.
In C, there is for (init; cond; advance). We all know that.
In Python there are two ways to loop over i=A..B (numerical.):
1) i = A
while i<B:
...do something...
i+=STEP


This is indeed quite ugly. You rarely need such loops in Python and
with some thinking you can often translate the C-equivalent to
something more pythonic. As you guessed, your second problem is best
solved with a generator function - xrange(). It is completely equal to
range() except that it returns a generator instead of a list.


It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1

There has to be a better way...

Any thoughts?

James

-----------------
7. Obsession with National Security
Fear is used as a motivational tool by the government over the masses.

Jul 18 '05 #12
James Stroud wrote:
It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1

There has to be a better way...


somelist[:] = [ item for item in somelist if not oughta_pop_it(item) ]

Kent
Jul 18 '05 #13
James Stroud wrote:


It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1

There has to be a better way...

Do you have to modify your list in place?

If not, just create a copy with the filtered items:

somelist = [item for item in somelist if not oughta_pop_it(item)]

or you could use filter or itertools.ifilter to do much the same thing

Michael

Jul 18 '05 #14
On Thu, 17 Feb 2005 10:22:01 -0800, James Stroud wrote:
It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1

There has to be a better way...

Any thoughts?


Others have pointed out

somelist = [x for x in somelist if not oughta_pop_it(x)]

but I'd also point out what I haven't seen, that your algorithm is O(n^2)
making fairly reasonable assumptions, whereas the list comprehension is
O(n). For long lists, that adds up fast. In fact, if you pop two things
off in the first half of the list, you've already lost and everything
after that is a waste.

The only time you want to do that is when you're memory-constrained, since
it will take less memory... and I gotta say, I don't think Python is the
best "memory-constrained" language in the world :-) Besides, if you're
really dealing with that much data, it's probably time to use a database
of some sort and tell *it* what things to eliminate.
Jul 18 '05 #15
James Stroud wrote:

It seems I need constructs like this all of the time

i = 0
while i < len(somelist):
if oughta_pop_it(somelist[i]):
somelist.pop(i)
else:
i += 1

There has to be a better way...


! for i in xrange(len(somelist)-1, -1, -1):
! if oughta_pop_it(somelist[i]):
! del somelist[i] # why use pop??

We don't need no stinking iterators; we're the
Python_1.5_or_earlier_istas!

Jul 18 '05 #16

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

Similar topics

23
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else:...
17
by: Istvan Albert | last post by:
Paul McGuire wrote: > Please reconsider the "def f() :" construct. Instead of > invoking a special punctuation character, it uses context and placement, > with familiar old 's, to infuse the...
0
by: Koen | last post by:
Hi! What is the best way to check whether a key is pressed without blocking in C++? I know I can use cin.get(c) to get a character from standard input, but this blocks. And I know _kbhit()...
8
by: lancevictor | last post by:
I'm learning javascript, and toward that end, I am recreating a page "my way". The original page: http://stenbergcollege.com and the one that I'm creating:...
11
by: ajikoe | last post by:
Hello, I used Visual C# Standard Edition. I want to comment my program using xml commentary method, I don't know why if I use value and example tag, it is not working / showed in the html...
21
by: Helge Jensen | last post by:
I've got some data that has Set structure, that is membership, insert and delete is fast (O(1), hashing). I can't find a System.Collections interface that matches the operations naturally offered...
28
by: Andre | last post by:
Hi, Does anyone know whether the ECMA, or an other standard document, specifies a maximum for the value that can be pass to the setTimeOut() function in Javascript? Andre
10
by: s.lipnevich | last post by:
Hi All, I apologize if this was brought up before, I couldn't find any "prior art" :-). On more than one occasion, I found myself wanting to use a "conditional loop" like this (with "Invalid...
1
by: abilashnn | last post by:
'm attempting to send a mailto: and include a link in the body. Has anyone done this? I have one problem with this. One appln have a link to send an email using “mailto:”. Previosly this...
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: 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...
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
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
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.