Home > Net >  Why cannot print a list like this in python?
Why cannot print a list like this in python?

Time:10-05

EDIT: after comments

Say I have list of class objects

lis = [Cls(i*1.0) for i in range(1,3,1)]

and the __str__ and __repr__ functions are also equipped.

class Cls:
    def __init__(self:object, inp:float)->None:
        self._inp = inp
   
    def __str__(self):
        return f'Cls_str: r={self._inp}'

    def __repr__(self):
        return f'Cls_repr: r={self._inp}'

    @property
    def inp(self):
        return self._inp

    @inp.setter
    def inp(self,value:float=0):
        self._inp=float(value)

    @inp.deleter
    def inp(self)->inp.deleter:
        del self._inp

then instead of for i in range(2,len(lis),1): print(lis[i]), it is expected to print like this. But it failed...

    print(lis[i]) for i in range(2,len(lis),1) # either
    print(lis[i] for i in range(2,len(lis),1))

CodePudding user response:

You can try unpacking using *:

print(*lst[2:],sep='\n')

OR

print(*(list[i] for i in range(2,len(list),1),sep='\n')

CodePudding user response:

you can print is like this:

for i in range(2,len(list),1):
    print(list[i])

or if that doesn't suits you, you can print it like this:

[print(list[i]) for i in range(2,len(list),1)]
  • Related