Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a non-iterable to list.extend ()

Tags:

python

list

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 be 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.

like image 595
JS. Avatar asked Nov 30 '22 10:11

JS.


1 Answers

You can check if the passed parameter is a list with the isinstance() function.

An even better solution could be to support a variable number of arguments:

def write_to_device(*args):
   # |args| is now a list of all the arguments given to the function
   input_list.extend(args)

This way multiple values can be given to the function even without having to explicitly specify them as a list:

write_to_device(1)
write_to_device(1,2,3)
like image 105
sth Avatar answered Dec 05 '22 05:12

sth