'Last number of iterator in python

How to edit the iterator giving also the last number in the sequence, please? I mean in general, not for such an easy sequence. Using < instead of == is not an option.

class P():
    def __init__(self, n0):
        self.n = n0

    def __iter__(self):
        return self
    
    def __next__(self):
        if self.n == 1:
            raise StopIteration
        num = self.n
        self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
        return num

nmax = 1000
PP = P(nmax)

PPP = []

for j in PP:
    PPP.append(j) 

print(PPP)

Current output:

[10, 5, 16, 8, 4, 2]

Desired output:

[10, 5, 16, 8, 4, 2, 1]



Solution 1:[1]

Use a local variable in your class to determin how many time you have get a next one:

class P():
    i = 0
    def __init__(self, n0):
        self.i=n0-1
        self.n = n0

    def __iter__(self):
        return self
    
    def __next__(self):
        self.i=self.i-1
        if self.i == 1:
            raise StopIteration
        num = self.n
        self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
        return num

nmax = 10
PP = P(nmax)

PPP = []

for j in PP:
    PPP.append(j) 

print(PPP)

NOTE: Generally it is safer to write: if self.i <= 1: then if self.i == 1:. In some future change you might change the value of i, and start decrementing it with 2, adn then the == variant will fail.

EDIT: When you want to stop when the previous value equals to 1, you can do:

class P():
    previous_value = 0
    def __init__(self, n0):
        self.i=n0-1
        self.n = n0

    def __iter__(self):
        return self
    
    def __next__(self):
        if self.previous_value == 1:
            raise StopIteration
        num = self.n
        self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
        self.previous_value = num
        return num

nmax = 20
PP = P(nmax)

PPP = []

for j in PP:
    PPP.append(j) 

print(PPP)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1