8

Is there a simple way to append a list if X is a string, but extend it if X is a list? I know I can simply test if an object is a string or list, but I was wondering if there is a quicker way than this?

3
  • 3
    The quickest and simplest way is to write code that doesn't force you later to do this. Commented Jan 21, 2011 at 15:58
  • Not possible in this particular circumstance, I'm inheriting X from a backend system and it won't pass single objects as list items Commented Jan 21, 2011 at 16:00
  • 1
    "it won't pass single objects as list" Sad. And you can't wrap it with a sensible function or extend it with extra methods or subclass it to fix it? Commented Jan 21, 2011 at 16:35

3 Answers 3

12

mylist.extend( [x] if type(x) == str else x )

or maybe the opposite would be safer if you want to catch things other than strings too:

mylist.extend( x if type(x) == list else [x] )

Sign up to request clarification or add additional context in comments.

2 Comments

I forgot about isinstance(), which would probably be more flexible than type()
Used the second of these, work pretty well, and is a little quicker than using ifs - my thanks
0

I do not think so. extend takes any iterable as input, and strings as well as lists are iterables in python.

Comments

0
buffer = ["str", [1, 2, 3], 4] myList = [] for x in buffer: if isinstance(x, str): myList.append(x) elif isinstance(x, list): myList.extend(x) else: print("{} is neither string nor list".format(x)) 

A better way would be using try-except instead of isinstance()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.