Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
popping an iterator
#1
i can easily extract the last item from a list with mylist.pop(). is there an easy way to do that with an iterator?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
import time.TimeMachine , use the future method to get the item at the end of the iterator.
Reply
#3
An iterator isn't a specific type of object. Lists are iterators. Some iterators have an accessible last item and some do not.

You can iterate over an object like itertools.count which has no fixed length and no "end". So the most general answer is no.
Reply
#4
(Oct-01-2021, 06:35 PM)Yoriz Wrote: import time.TimeMachine , use the future method to get the item at the end of the iterator.

i guess this must run the iterator since it could be a generator or such.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
(Oct-01-2021, 06:35 PM)Yoriz Wrote: import time.TimeMachine , use the future method to get the item at the end of the iterator.

i don't seem to have time.TimeMachine. i'm still on Python 3.6. i hope to be on 3.9 soon.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Somehow I don't think that was a serious suggestion..
Yoriz likes this post
Reply
#7
Also, what would you think should happen if the iterator was infinitely long?

It sounds like you've already come up with the solution to a problem, but it might help if you told us what the problem really is. Why do you want to do that? What are you trying to achieve, at a high level?
Reply
#8
Write your custom iterable/iterator

from collections.abc import Sequence


class SeekableIterator:
    def __init__(self, sequence):
        if not isinstance(sequence, Sequence):
            raise ValueError("No!")
            
        self.sequence = sequence
        self.index = 0

    def seek(self, position):
        if 0 <= position <= len(self):
            self.index = position
        else:
            raise ValueError("Position out of range")
                
    def seek_relative(self, position):
        if 0 <= (new_index := self.index + position) <= len(self):
            self.index = new_index
        else:
            raise ValueError("Position out of range")
        
    @property
    def first(self):
        if self.sequence:
            return self.sequence[0]
    
    @property
    def last(self):
        if self.sequence:
            return self.sequence[-1]    

    def __reversed__(self):
        """
        Returns a new instance of SeekableIterator
        and the sequence is a reversed copy of the old
        """
        return self.__class__(self.sequence[::-1])

    def __len__(self):
        return len(self.sequence)
        
    def __iter__(self):
        return self.__class__(self.sequence)
    
    def __next__(self):
        if self.index <= len(self) - 1:
            value = self.sequence[self.index]
            self.index += 1
            return value
        else:
            raise StopIteration



iterator = SeekableIterator(["a", "b", "c"])
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#9
i did find something called time_machine for CPython on Unix. it was a "PRE_LOAD" binary library that allowed setting fake clock values. it probably intercepted syscalls that get the time and added/subtracted a time offset. i think Linux can already do that in containers which would not let the same Python script control it (you'd have to create containers from Python and run something in them).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#10
does reversed() work on iterators? ... nope!
Output:
lt2a/phil /home/phil 16> box try_rev.py +----<try_rev.py>----+ | a=[1,2,3,4,5,6] | | b=iter(a) | | c=reversed(b) | | print(c[0]) | +--------------------+ lt2a/phil /home/phil 17> py try_rev.py Traceback (most recent call last): File "try_rev.py", line 3, in <module> c=reversed(b) TypeError: 'list_iterator' object is not reversible lt2a/phil /home/phil 18>
i think it's time for me to create a function named revit.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  prime numbers with iterator and generator cametan_001 8 1,875 Dec-17-2022, 02:41 PM
Last Post: cametan_001
  resetting an iterator to full Skaperen 7 6,997 Feb-20-2022, 11:11 PM
Last Post: Skaperen
  q re glob.iglob iterator and close jimr 2 2,241 Aug-23-2021, 10:14 PM
Last Post: perfringo
  Problem with an iterator grimm1111 9 4,338 Feb-06-2021, 09:22 PM
Last Post: grimm1111
  Multi-class iterator Pedroski55 2 2,396 Jan-02-2021, 12:29 AM
Last Post: Pedroski55
  is a str object a valid iterator? Skaperen 6 5,650 Jan-27-2020, 08:44 PM
Last Post: Skaperen
  discard one from an iterator Skaperen 1 1,997 Dec-29-2019, 11:02 PM
Last Post: ichabod801
  how do i pass duplicates in my range iterator? pseudo 3 2,364 Dec-18-2019, 03:01 PM
Last Post: ichabod801
  looking for a sprcil iterator Skaperen 7 3,370 Jun-13-2019, 01:40 AM
Last Post: Clunk_Head
  last pass of for x in iterator: Skaperen 13 5,896 May-20-2019, 10:05 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020