Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old May 4th, 2005, 8:26 AM   #1
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile Using reversed and next

It was al1986 who got me into this ...

The reversed() function returns an iterator object. Try invoking a next() method on this object. Alternatively, you can loop through the items by doing
for i in mysortedlist: print i

So I tried this ...
x = [1,2,3,4]
print "original list =", x
rx = reversed(x)
for i in rx: print i,
print

Then this ...
x = [1,2,3,4]
print "original list =", x
rx = reversed(x)
print "rx.next() =", rx.next()
print "rx.next() =", rx.next()
print "rx.next() =", rx.next()

When I combine the two codes I get an error that does not like next() or rx ...
x = [1,2,3,4]
print "original list =", x
rx = reversed(x)
for i in rx: print i,
print
print "rx.next() =", rx.next()
print "rx.next() =", rx.next()
print "rx.next() =", rx.next()
It acts like rx has been soiled, any idea what is going on?
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Old May 4th, 2005, 7:36 PM   #2
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by Dietrich
It acts like rx has been soiled, any idea what is going on?
When you do for i in rx..., you entirely consume the iterator. An iterator will raise a StopIteration when it has no more elements to yield:
x = iter(range(4))
for i in x:
    print i
    if i%2:
        break
print "!!"
print x.next()
print x.next()
print x.next()  # <--Boom

--OH.
hydroxide is offline   Reply With Quote
Old May 4th, 2005, 9:08 PM   #3
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile

Thanks hydroxide!

When I did a few print rx to check, the iterator seemed to be unchanged.
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 9:57 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC