2

Here is my simplified code as i can't post my actual code in python 3:

class example(object):
    def __init__(self, list1):
        self.list1 = list1
    def __repr__(self):
        if len(self.list1) > 0:
            for i in self.list1:
                for j in range(1,len(self.list1)):
                    return ('{0:}{1:}').format(j, i)

x = example(['this', 'is', 'a', 'list'])
x

This should return:

1this

Now im wanting it to return:

1this
2is
3a
4list

How do i go about doing this?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
snuffles101
  • 61
  • 2
  • 9

1 Answers1

2

Just use enumerate function as follows:

class example(object):
    def __init__(self, list1):
        self.list1 = list1
    def __repr__(self):
        return '\n'.join('{0}{1}'.format(c+1, el) for c, el in enumerate(self.list1))
dopstar
  • 1,478
  • 10
  • 20
  • better: return '\n'.join('{0}{1}'.format(c, el) for c, el in enumerate(self.list1,1)) – mmachine Oct 17 '15 at 13:45
  • I prefer `enumerate` to be always be zero-based and add the offset myself. I dont think `c+1` has any perfomance penalty of significance. And `c+1` is self explanatory. – dopstar Oct 17 '15 at 13:59