473,503 Members | 12,516 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

python loops

In C and C++ and Java, the 'for' statement is a shortcut to make very
concise loops. In python, 'for' iterates over elements in a sequence.
Is there a way to do this in python that's more concise than 'while'?

C:
for(i=0; i<length; i++)
python:
while i < length:
i += 1

Aug 31 '06 #1
10 3948
Putty wrote:
In C and C++ and Java, the 'for' statement is a shortcut to make very
concise loops. In python, 'for' iterates over elements in a sequence.
Is there a way to do this in python that's more concise than 'while'?

C:
for(i=0; i<length; i++)
python:
while i < length:
i += 1
for i in range(length):
print i
--
--
There are several things that I will never be:
* I will never be attracted to females.
* I will never enjoy the company of others.
Exactly how these realities bode for my enemy, is not of my concern.

Aug 31 '06 #2
AlbaClause wrote:
for i in range(length):
print i
Or usually better:

for ii in xrange(length):
...

Bye,
bearophile

Aug 31 '06 #3
Putty wrote:
In C and C++ and Java, the 'for' statement is a shortcut to make very
concise loops. In python, 'for' iterates over elements in a sequence.
Is there a way to do this in python that's more concise than 'while'?

C:
for(i=0; i<length; i++)
python:
while i < length:
i += 1
As AlbaClause had demonstrated you can iterate over indices as well
using the for-statement and the range() function. But you can also
combine iterating over elements and indices at the same time using the
builtin enumerate() type:

for i, item in enumerate(("s1","s2")):
print i,item

0 s1
1 s2

Aug 31 '06 #4

be************@lycos.com wrote:
AlbaClause wrote:
for i in range(length):
print i

Or usually better:

for ii in xrange(length):
~~

I hate ii ;)

Regards,
Kay

Aug 31 '06 #5
Kay Schluehr:
I hate ii ;)
It's not nice looking, I agree. A more explicit name is often better.
But I think ii is better than i because you can find it in the code
(with the Find command of the editor or grep) more easily than i.

Bye,
bearophile

Sep 1 '06 #6

Putty wrote:
In C and C++ and Java, the 'for' statement is a shortcut to make very
concise loops. In python, 'for' iterates over elements in a sequence.
Is there a way to do this in python that's more concise than 'while'?

C:
for(i=0; i<length; i++)
python:
while i < length:
i += 1
Someone else gave an apt reply to a similar question before, but I
don't know when so I'll give the gist:
In languages like C and Java, the for loop index variable is often used
to iterate over members of a sequence or other data type.
In Python many of the data types can be directly iterated over without
having to increment a separate indexing value.

C type language:

length = length_finder(some_datatype);
for(i=0; i<length; i++){
indexed_data = some_datatype[i]
do_stuff(indexed_data)
}

Becomes the more elegant Python:

for indexed_data in some_datatype:
do_stuff(indexed_data)
- Paddy.

Sep 1 '06 #7
be************@lycos.com wrote:
>AlbaClause wrote:
>for i in range(length):
print i

Or usually better:

for ii in xrange(length):
...
xrange used to be better. As I understand it, that's no longer the case.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Sep 3 '06 #8
Tim Roberts wrote:
xrange used to be better. As I understand it, that's no longer
the case.
for short ranges, range is faster in some Python versions, xrange is
faster in some (including 2.4). the difference is usually very small
(the same number of objects are created in both cases).

for long ranges, especially when it's likely that you won't actually
need all the values, xrange is better.

if you *need* a list, range is better.

in python 3.0, range will return an iterator, and xrange will disappear.
if you need a list in 3.0, you will have to do list(range(N)).

</F>

Sep 3 '06 #9
Tim Roberts <ti**@probo.comwrote:
...
xrange used to be better. As I understand it, that's no longer the case.
measuring is better than guessing:

brain:~/codejam alex$ python -V
Python 2.5c1
brain:~/codejam alex$ python -mtimeit 'for x in range(1000):pass'
10000 loops, best of 3: 71.9 usec per loop
brain:~/codejam alex$ python -mtimeit 'for x in xrange(1000):pass'
10000 loops, best of 3: 54 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=range(1000)' 'for x in
y:pass'
10000 loops, best of 3: 44.8 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=xrange(1000)' 'for x in
y:pass'
10000 loops, best of 3: 53.2 usec per loop
brain:~/codejam alex$

So: in 2.5 (2.4 too, do your own timings;-) range is better if you can
create the range once and use it repeatedly, xrange if you have to
create the range each time. But actually:

brain:~/codejam alex$ python -mtimeit -s'from itertools import repeat'
'for x in repeat(None, 1000): pass'
10000 loops, best of 3: 41.3 usec per loop

if you don't actually need the iteration-index in the loop (you just
need to repeat the loop N times), itertools.repeat is even better (well,
if every microsecond counts, anyway;-).
Alex
Sep 9 '06 #10
Jay
Here are my benchmarks for those interested in version 2.4.3

jsherby@montauk:~$ python -V
Python 2.4.3
jsherby@montauk:~$ python -mtimeit 'for x in range(1000):pass'
10000 loops, best of 3: 64.2 usec per loop
jsherby@montauk:~$ python -mtimeit 'for x in xrange(1000):pass'
10000 loops, best of 3: 50.5 usec per loop
jsherby@montauk:~$ python -mtimeit -s'y=range(1000)' 'for x in y:pass'
10000 loops, best of 3: 68.2 usec per loop
jsherby@montauk:~$ python -mtimeit -s'y=xrange(1000)' 'for x in y:pass'
10000 loops, best of 3: 51.4 usec per loop
jsherby@montauk:~$ python -mtimeit -s'from itertools import repeat'
'for x in repeat(None, 1000): pass'
10000 loops, best of 3: 45.6 usec per loop
jsherby@montauk:~$

Alex Martelli wrote:
Tim Roberts <ti**@probo.comwrote:
...
xrange used to be better. As I understand it, that's no longer the case.

measuring is better than guessing:

brain:~/codejam alex$ python -V
Python 2.5c1
brain:~/codejam alex$ python -mtimeit 'for x in range(1000):pass'
10000 loops, best of 3: 71.9 usec per loop
brain:~/codejam alex$ python -mtimeit 'for x in xrange(1000):pass'
10000 loops, best of 3: 54 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=range(1000)' 'for x in
y:pass'
10000 loops, best of 3: 44.8 usec per loop
brain:~/codejam alex$ python -mtimeit -s'y=xrange(1000)' 'for x in
y:pass'
10000 loops, best of 3: 53.2 usec per loop
brain:~/codejam alex$

So: in 2.5 (2.4 too, do your own timings;-) range is better if you can
create the range once and use it repeatedly, xrange if you have to
create the range each time. But actually:

brain:~/codejam alex$ python -mtimeit -s'from itertools import repeat'
'for x in repeat(None, 1000): pass'
10000 loops, best of 3: 41.3 usec per loop

if you don't actually need the iteration-index in the loop (you just
need to repeat the loop N times), itertools.repeat is even better (well,
if every microsecond counts, anyway;-).
Alex
Sep 9 '06 #11

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

Similar topics

14
2628
by: 2mc | last post by:
Generally speaking, if one had a list (from regular Python) and an array (from Numerical Python) that contained the same number of elements, would a While loop or a For loop process them at the...
15
2486
by: Guyon Morée | last post by:
Hi all, I am working on a Huffman encoding exercise, but it is kinda slow. This is not a big problem, I do this to educate myself :) So I started profiling the code and the slowdown was...
114
9691
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
30
3437
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course,...
6
2231
by: Gonzalo Monzón | last post by:
Hi all! I have been translating some Python custom C extension code into Python, as I need these modules to be portable and run on a PocketPC without the need of compile (for the purpose its a...
11
1233
by: John Nagle | last post by:
How naive (in the sense that compiler people use the term) is the current Python system? For example: def foo() : s = "This is a test" return(s) s2 = foo() How many times does the string...
18
2947
by: Marko.Cain.23 | last post by:
Hi, I create a dictionary like this myDict = {} and I add entry like this: myDict = 1 but how can I empty the whole dictionary? Thank you.
145
4156
by: Dave Parker | last post by:
I've read that one of the design goals of Python was to create an easy- to-use English-like language. That's also one of the design goals of Flaming Thunder at http://www.flamingthunder.com/ ,...
0
7212
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
7098
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
7364
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
7470
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...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
4696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1524
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.