473,388 Members | 866 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,388 software developers and data experts.

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 3942
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
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
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
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
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
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
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
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
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...

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.