473,668 Members | 2,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 64513
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.c omwrote:
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.c omwrote:
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.c om>:
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

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

Similar topics

0
1354
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 on listobject.h, i create the src file vectorobject.c based on listobject.c and intobject.c. 1 i had create PyVectorObject like this typedef struct { PyObject_VAR_HEAD double* ob_item; } PyVectorObject;
6
3642
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 In FileInfo If Thing.Displayed <> True Then GoTo Iterate 'skip this entry; try next one End If
3
1800
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 make a table with 2 columns and then for every one, depending on its position in the string i need to output a word and then go to the next 1 and output a dif word.... its amenities, winter activities and summer activities for cottages that i...
5
4071
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 be printed reverse so instead doing "print e, d, c, b, a", I'd like to use the reverse function Can someone give pointersguidelines / on how to do it?
5
10462
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 option. Consequently, the makefile fails, since it can't find the targets/dependencies. 2. After searching around, it seems that os.system(..) should be avoided if there's an alternative. Is there one in this case?
2
1906
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
1827
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
1828
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
137
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? And it won't work either.....integer math
7
5346
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 in the BeforeUpdate event for the form. This I can do...the fun part is that I want to do it in reverse so that when I call the SetFocus method, it goes to the first control that is empty as opposed to the last one. To loop forward, I've used...
0
8381
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8797
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8656
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6209
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4205
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2791
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 we have to send another system
2
2023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1786
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.