Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python extend or append a list when appropriate

Tags:

python

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?

like image 308
chrism Avatar asked Jan 21 '11 15:01

chrism


People also ask

When to use append and extend in Python?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list. Argument: . append() takes a single element as argument while .

What is the difference between appending a list and extending a list?

append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list.

Is append or extend faster Python?

As we can see, extend with list comprehension is still over two times faster than appending.


1 Answers

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] )

like image 149
kurosch Avatar answered Sep 27 '22 18:09

kurosch