473,383 Members | 1,717 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,383 software developers and data experts.

Loop Backwards

This should be simple, but I can't get it:

How do you loop backwards through a list?

For example, in, say, javascript:

for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}

I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.

Thanks!

- Dave

Feb 14 '06 #1
10 4189

Dave wrote:
This should be simple, but I can't get it:

How do you loop backwards through a list?

For example, in, say, javascript:

for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}

I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.
Negative indexes start at the opposite end than positive indexes.
s = [1,2,3,4,5]
for i in range(len(s)): print s[-i-1],

5 4 3 2 1



Thanks!

- Dave


Feb 14 '06 #2
Thanks! I knew it was simple...

Feb 14 '06 #3
Dave wrote:
This should be simple, but I can't get it:

How do you loop backwards through a list?

For example, in, say, javascript:

for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}

I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.

Thanks!

- Dave


for i in reversed(ls):
do_stuff()

reversed doesn't reverse the list. It returns an iterator that iterates
through the list backwards.

Cheers,
Carl.
Feb 14 '06 #4

me********@aol.com wrote:
Dave wrote:
This should be simple, but I can't get it:

How do you loop backwards through a list?

For example, in, say, javascript:

for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}

I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.


Negative indexes start at the opposite end than positive indexes.
s = [1,2,3,4,5]
for i in range(len(s)):

print s[-i-1],

5 4 3 2 1

I thought the python way is to use slice :

range(10)[::-1]

Feb 14 '06 #5

Dave> This should be simple, but I can't get it:
Dave> How do you loop backwards through a list?

Standard idiom:

for i in range(len(mylist)-1, -1, -1):
do_stuff()

Contrast that with the standard forward loop:

for i in range(len(mylist)):
do_stuff()

So, to go backwards, just add "-1, -1, -1" to the range function in the
forward loop version.

Skip
Feb 14 '06 #6
Dave wrote:
This should be simple, but I can't get it:

How do you loop backwards through a list?

For example, in, say, javascript:

for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}

I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.


for item in reversed(alist):
do_something_with(item)

or (more perlish at first sight):

for item in alist[::-1]:
do_something_with(item)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Feb 14 '06 #7
Em Ter, 2006-02-14 Ã*s 10:08 +0100, bruno at modulix escreveu:
for item in reversed(alist):
do_something_with(item)

or (more perlish at first sight):

for item in alist[::-1]:
do_something_with(item)


No "or" here. The [::-1] version creates a whole new list in memory,
it's silly to believe both will behave equally (well, strictly speaking
they will, but one will use twice more memory than the other).

--
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

-- Sun Tzu, em "A arte da guerra"

Feb 14 '06 #8
>> or (more perlish at first sight):
for item in alist[::-1]:
do_something_with(item)
No "or" here. The [::-1] version creates a whole new list in memory,
it's silly to believe both will behave equally (well, strictly speaking
they will, but one will use twice more memory than the other).


Thank you for your reply.

Please be mindful of making statements such as:
"it's silly to believe both will behave equally"

One of the greatest weaknesses of Python is the less than friendly
attitude Pythonistas display towards one another. Bruno's suggestions
were valid, given the original question. Even if I had asked for the
most efficient method of iterating through a list in reverse, this
response is unwarranted.

This example is why everyone is more excited about Ruby than Python. If
we become more friendly to each other, Python will win!

Mar 15 '06 #9
"Dave" <da*********@gmail.com> wrote:

Please be mindful of making statements such as:
"it's silly to believe both will behave equally"

One of the greatest weaknesses of Python is the less than friendly
attitude Pythonistas display towards one another.
I don't know how much Usenet experience you've had, but comp.lang.python is
one of the friendliest places in the comp.lang universe. Newbie questions
get answered without derision, and disagreements are handled with spirited
discussion, instead of flames and insults. Compare, for example, to
comp.lang.c and comp.lang.c++.
This example is why everyone is more excited about Ruby than Python.


That statement is just not true. I've looked at Ruby, but syntactically it
will never sway me from Python.
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Mar 17 '06 #10

Tim Roberts wrote:
"Dave" <da*********@gmail.com> wrote:

Please be mindful of making statements such as:
"it's silly to believe both will behave equally"

One of the greatest weaknesses of Python is the less than friendly
attitude Pythonistas display towards one another.
I don't know how much Usenet experience you've had, but comp.lang.python is
one of the friendliest places in the comp.lang universe. Newbie questions
get answered without derision, and disagreements are handled with spirited
discussion, instead of flames and insults. Compare, for example, to
comp.lang.c and comp.lang.c++.


It's possible that english may not be Felipe's native language,
and Dave may not've thought of that. To a native english speaker,
Felipe's comment (which was very helpful!) could've also been
construed as being slightly rude. Perhaps Felipe meant to write
"mistaken" instead of "silly".

Also, as an aside, smileys are always helpful on usenet. :)
[snip] I've looked at Ruby, but syntactically it
will never sway me from Python.


Same here.

Mar 17 '06 #11

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

Similar topics

11
by: Wayne Folta | last post by:
Two observations about PEP-315: 1. It's clever, addresses a definite "wart", and is syntactically similar to try/except. But it's syntax seems like an acquired taste to me. 2. It is a very...
25
by: skull | last post by:
Hi everybody, it is my first post in this newsgroup. I am a newbie for python though I have several years development experience in c++. recently, I was stumped when I tried to del item of a list...
18
by: Ken Varn | last post by:
Is there any way to reset a foreach loop to re-iterate through the collection as if it were starting from the beginning? Namely, if I delete an item out of a collection, I want to be able to reset...
2
by: ad | last post by:
I want to delete a DataRowView in a DataView if the DataRowView not checked OK. (CheckRow is a function for checking ) I used the codes below: But when some row is delete, it fail , the error...
6
by: samuel.y.l.cheung | last post by:
Hi, I am trying to convert a Java iterator loop to C++ STL? the loop looks like this: public static boolean func (List aList) { int minX = 0 for (Iterator iter = aList.listIterator(1);...
29
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is:...
10
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I wanted to go through each entry(?) of ArrayList and remove some particular entry. So I tried following but it throws exception at runtime: foreach (myEntry entry in myArrayList) {...
1
by: Peter Duniho | last post by:
On Sat, 17 May 2008 16:36:17 -0700, <msnews.microsoft.comwrote: Sounds like a homework problem. Here's a hint: if you want your loop to go backwards, adding to (incrementing) the counter...
7
beacon
by: beacon | last post by:
Hi everybody, This may be an easy one, but I'm having a lot of trouble with it. I have a continuous form and I want to validate that the user has entered something in each of the required fields...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
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?
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...

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.