Python - Neaten this append/extend conditional
append, extend, list, python
Solution
def append(self, item):
self.list.append(item)
def extend(self, item):
self.list.extend(item)
Bottom line: Don't have a method to do both things. It confuses and makes your method less useful, instead of more useful. It's also harder to test and to maintain. Also the user of your function already knows if she wants to use append or extend, so by providing a single method you're discarding the information your caller/user already knows.
Another way to write is using packing/unpacking argument syntax:
def append(self, *items):
self.list.extend(items)
that way you can call the method as
x.append('single item')
or
x.append(*list_of_items)
Problem
I have a method which I will accept either a single object or a list of objects. I want to add whatever is passed to another list. Currently, my method looks like this: ``` def appendOrExtend(self, item): if type(item).__name__ == "list": self.list.extend(item) else: self.list.append(item) ``` It seems to me that there should be a more Pythonic way of achieving this, could you suggest one?