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

How to make a reverse for loop in python?

Hello

I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
Sep 20 '08 #1
15 64471
Alex Snast a écrit :
Hello

I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
for (i = 0; i < 10; i--) -for i in range(10):

for (i = 10; i >= 0; --i) -for i in range(10,-1,-1):

Thoma
Sep 20 '08 #2
On Sep 20, 11:16�am, Alex Snast <asn...@gmail.comwrote:
Hello

I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
>>for i in xrange(10,-1,-1): print i,
10 9 8 7 6 5 4 3 2 1 0

Note the starting number is 10, the ending
number is -1 because you want to include 0
and the step size is -1.
Sep 20 '08 #3
Alex Snast <as****@gmail.comwrote:
Hello

I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
The exact equivalent would be:

for i in range(10, -1, -1): print i

except you virtually never want to do that in Python. Don't expect just to
translate statement by statement from one language to another: normally in
Python you will iterate directly over the sequence you want to process
rather than trying to count loop indices with all the telegraph pole errors
that result.

The usual way to iterate over a sequence in reverse is:

for x in reversed(seq): print x

although if you know it is a list, string or other object that supports
extended slicing you can also do:

for x in seq[::-1]: print x

this may be less clear than using 'reversed', but does allow you to specify
an explicit start, stop and step if you want to do only part of the
sequence.
Sep 20 '08 #4
2008/9/20 Alex Snast <as****@gmail.com>:
I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
for i in range(10, 0, -1):
print i

--
Cheers,
Simon B.
Sep 20 '08 #5
Alex Snast wrote:
I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
use range with a negative step:

for i in range(10-1, -1, -1):
...

or just reverse the range:

for i in reversed(range(10)):
...

(the latter is mentioned in the tutorial, and is the second hit if you
google for "python reverse for loop")

</F>

Sep 20 '08 #6
Alex Snast wrote:
Hello

I'm new to python and i can't figure out how to write a reverse for
loop in python

e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)
--
http://mail.python.org/mailman/listinfo/python-list
What are you trying to loop through?

If it's the contents of a list, you can reverse the list (in place) first:

L = [1,2,3]
L.reverse()
for item in L:
print item

Or you can create a new reversed (copy of the original) list and iterate
through it

for item in reversed(L):
print item

If it's just a sequence of numbers you want to generate:

range(3) generates a forward list [0,1,2], and
range(3,0,-1) generates a backward list [2,1,0]

so

for i in range(11,0,-1):

might be what you want.
If your list is huge, consider xrange rather than range.
And as always, you could just roll your own index manipulation:

i = 10
while i >=0:
# do whatever
i -= 1


Gary Herron
Sep 20 '08 #7
Fredrik Lundh wrote:
>e.g. the python equivalent to the c++ loop

for (i = 10; i >= 0; --i)

use range with a negative step:

for i in range(10-1, -1, -1):
...

or just reverse the range:

for i in reversed(range(10)):
...
(and to include the 10 in the range, add one to the 10 above)

</F>

Sep 20 '08 #8
Gary Herron wrote:
Or you can create a new reversed (copy of the original) list and iterate
through it

for item in reversed(L):
Â* print item
It's not a copy, it's a view:
>>items = [1,2,3]
r = reversed(items)
items[:] = "abc"
for item in r: print item
....
c
b
a

Peter
Sep 20 '08 #9
Duncan Booth:
e.g. the python equivalent to the c++ loop
for (i = 10; i >= 0; --i)

The exact equivalent would be:
for i in range(10, -1, -1): print i
I'd use xrange there. Anyway, I have always felt that Python syntax
not easy to understand at first sight, expecially when you try to
convert a bit more complex inverted for loops from/to C to/from
Python. It's one of the few cases where (for example) Pascal (loop)
syntax wins a bit over Python syntax :-)

Bye,
bearophile
Sep 20 '08 #10
On Sep 20, 8:13*pm, bearophileH...@lycos.com wrote:
Duncan Booth:
e.g. the python equivalent to the c++ loop
for (i = 10; i >= 0; --i)
The exact equivalent would be:
* * * * for i in range(10, -1, -1): print i

I'd use xrange there. Anyway, I have always felt that Python syntax
not easy to understand at first sight, expecially when you try to
convert a bit more complex inverted for loops from/to C to/from
Python. It's one of the few cases where (for example) Pascal (loop)
syntax wins a bit over Python syntax :-)

Bye,
bearophile
That's a lot of responses guys. Thanks a lot i think i got it.
Another question, are there any pointers in python (or iterators) for
when i use
a data structure that doesn't support random access?

Thanks again, Alex
Sep 20 '08 #11
On Sep 20, 8:13*pm, bearophileH...@lycos.com wrote:
Duncan Booth:
e.g. the python equivalent to the c++ loop
for (i = 10; i >= 0; --i)
The exact equivalent would be:
* * * * for i in range(10, -1, -1): print i

I'd use xrange there. Anyway, I have always felt that Python syntax
not easy to understand at first sight, expecially when you try to
convert a bit more complex inverted for loops from/to C to/from
Python. It's one of the few cases where (for example) Pascal (loop)
syntax wins a bit over Python syntax :-)

Bye,
bearophile
Another quick question please, is the List data structure just a
dynamic array? If so how can you use static size array, linked list,
AVL trees etcetera.
Sep 20 '08 #12
Alex Snast wrote:
Another quick question please, is the List data structure just a
dynamic array? If so how can you use static size array, linked list,
AVL trees etcetera.
You should treat Python lists as an opaque item. You shouldn't concern
yourself with the implementation details. Python lists are fast and
optimized for most use cases. Unless you have specific needs for highly
specialized data types, use lists.

Just *don't* try to abuse lists by creating fancy stuff e.g. linked
lists. The memory overhead is going to kill your app.

Christian

Sep 21 '08 #13
En Sat, 20 Sep 2008 20:27:41 -0300, Alex Snast <as****@gmail.comescribió:
Another quick question please, is the List data structure just a
dynamic array? If so how can you use static size array, linked list,
AVL trees etcetera.
Yes, lists are implemented as dynamic arrays (but you shouldn't care about
it). "Textbook" linked lists are good for a CS course, but useless in most
usual circumstances (think of memory fragmentation). There are AVL trees
implemented in Python, but not built in.
Read the Python Tutorial specially this section
http://docs.python.org/tut/node7.html
You may be interested in the collections module too
http://docs.python.org/lib/module-collections.html

--
Gabriel Genellina

Sep 21 '08 #14
Christian Heimes:
Unless you have specific needs for highly specialized data types, use lists.
There's also the collections.deque for other related purposes.

(I suggest people willing to look at some nice C code to read the
sources of deque, Hettinger has created some refined code, very
readable).

Bye,
bearophile
Sep 21 '08 #15
On Sun, 21 Sep 2008 01:56:59 +0200, Christian Heimes wrote:
Just *don't* try to abuse lists by creating fancy stuff e.g. linked
lists. The memory overhead is going to kill your app.
I agree with your advice not to abuse lists, but not for the reason you
give. The memory overhead of a linked list implemented on top of a Python
list probably isn't going to be that much greater than a dict or a class.

I think the real reasons why linked lists get a bad rep in Python are:

(1) they're unnecessary 99% of the time;

(2) when they are necessary, a better implementation is to use classes
(e.g. see traceback objects); and

(3) the standard Lisp idiom for lists is horribly inefficient in CPython:

alist = [1, [2, [3, [4, [5, [6, []]]]]]]

But that's primarily inefficient because of the number of method calls
needed to access an item. There is some memory overhead, but memory is
cheap and the overhead of using objects in the first place is far larger
than the overhead of a few extra pointers.
--
Steven
Sep 21 '08 #16

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

Similar topics

0
by: elsejj | last post by:
i want make a new object named 'vector' to my python release, the 'vector' is most like a 'list', but have some number operatioins such as add, sub, ect. i create the head file vectorobject.h based...
6
by: eBob.com | last post by:
How do you make a loop iterate early without using a GoTo? (I guess I've done too much structured programming and I really don't like using GoTos.) Here's my code ... For Each Thing As OFI...
3
by: Kentor | last post by:
hello, im trying to make a little loop, but i cant figure it out... i have a string with a bunch of 1s and 0s in it: 110101010101111010101 .... i need to count the number of 1s divide it by 2 and...
5
by: frankie_85 | last post by:
Ok I'm really lost (I'm new to python) how to use the reverse function. I made a little program which basically the a, b, c, d, e which I have listed below and basically I want it th result to...
5
by: Efrat Regev | last post by:
Hello, I need to call GNU/make from within a Python script. This raised some problems: 1. The script is not in the directory of the makefile, and changing the locations of either is not an...
2
by: yinglcs | last post by:
Hi, I have a python script: At the end of the script, I have: print "Build Done!" my question is does that mean my python script exits after it prints "Build done!"
4
by: stefano | last post by:
I need make some images using python but i'm lost :P i need some module to make .png (with drawline, drawcircle, drawpoint etc etc etc ) like gd for php :P thants :D
1
by: Davy | last post by:
Hi all, How to make a standalone Python/Tk program(e.g. exe file on Windows)? Any suggestions are welcome! Best regards, Davy
1
by: Bill Butler | last post by:
----- Original Message ----- From: "Cor Ligthert" <notmyfirstname@planet.nl> Newsgroups: microsoft.public.dotnet.languages.csharp Sent: Sunday, May 18, 2008 12:05 AM Subject: Re: Reverse Loop? ...
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
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.