Passing a non-iterable to list.extend ()

Posted by JS on Stack Overflow See other posts from Stack Overflow or by JS
Published on 2010-04-06T21:03:12Z Indexed on 2010/04/06 21:13 UTC
Read the original article Hit count: 346

Filed under:
|

Hello,

I am creating a public method to allow callers to write values to a device, call it write_vals() for example.

Since these values will by typed live, I would like to simplify the user's life by allowing them type in either a list or a single value, depending on how many values they need to write. For example:

write_to_device([1,2,3])

or

write_to_device(1)

My function would like to work with a flat list, so I tried to be clever and code something like this:

input_list = []  
input_list.extend( input_val )

This works swimmingly when the user inputs a list, but fails miserably when the user inputs a single integer:

TypeError: 'int' object is not iterable

Using list.append() would create a nested list when a list was passed in, which would be an additional hassle to flatten.

Checking the type of the object passed in seems clumsy and non-pythonic and wishing that list.extend() would accept non-iterables has gotten me nowhere. So has trying a variety of other coding methods.

Suggestions (coding-related only, please) would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about python

Related posts about list