4

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 2

1

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} 
Sign up to request clarification or add additional context in comments.

3 Comments

Beware with cases where the words themselves contain commas.
Might it be more efficient to join on , and replace only the final one with and?
The words will never contain commas themselves.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.