Custom string representation of list depending on number of items (Python)

Viewed 50

I need to print out a list differently depending on how many items it has:

For example:

  • For no items i.e. [] should output {}
  • For 1 item i.e. ["Cat"] should output {Cat}
  • For 2 items i.e. ["Cat", "Dog"] should output {Cat and Dog}
  • For 3 or more items i.e. ["Cat", "Dog", "Rabbit", "Lion"] should output {Cat, Dog, Rabbit and Lion}

I currently am doing something like this with a bunch of if statements:

def customRepresentation(arr):
  if len(arr) == 0:
    return "{}"
  elif len(arr) == 1:
    return "{" + arr[0] + "}"
  elif len(arr) == 2:
    return "{" + arr[0] + " and " + arr[0] + "}"
  else:  
    # Not sure how to deal with the case of 3 or more items

Is there a more pythonic way to do this?

2 Answers

Assuming the words will never contain commas themselves. You could instead use join and replace to deal with all your cases in just one line:

>>> def custom_representation(l):
...   return "{%s}" % " and ".join(l).replace(" and ", ", ", len(l) - 2)
... 
>>> for case in [], ["Cat"], ["Cat", "Dog"], ["Cat", "Dog", "Rabbit", "Lion"]:
...   print(custom_representation(case))
... 
{}
{Cat}
{Cat and Dog}
{Cat, Dog, Rabbit and Lion} 

Here's how I'd go about this:

class CustomList(list):

    def __repr__(self):

        if len(self) == 0:
            return '{}'
        elif len(self) == 1:
            return '{%s}' % self[0]
        elif len(self) == 2:
            return '{%s and %s}' % (self[0], self[1])
        else:
            return '{' + ', '.join(str(x) for x in self[:-1]) + ' and %s}' % self[-1]

>>> my_list = CustomList()
>>> my_list
{}
>>> my_list.append(1)
>>> print(my_list)
{1}
>>> my_list.append('spam')
>>> print(my_list)
{1 and spam}
>>> my_list.append('eggs')
>>> my_list.append('ham')
>>> print(my_list)
{1, spam, eggs and ham}
>>> my_list
{1, spam, eggs and ham}

This way you have a fully functional list, only the representation is customised.

Related