I am trying to import the range A1:C4
from Excel into Python as a list, then add '_a' to the end of every element in that list. Currently it is returning the TypeError "can only concatenate list(not 'str') to list"
I've gotten it to import a range before then return that range:
#Excel formula: =funky(A1:C4)
listy = ["item_0"]
@xl_func #needed before any function that is called on in the excel spreadsheet
def funky(add): #needs one input to function, in this case it is being given the range A1:C4 in the excel spreadsheet
global listy
listy.extend(add) #adds all the elements given to the function into 'listy' (in this case it is the values of range A1:C4 in the excel spreadsheet)
return(listy[1:]) #returns all elements past element [0]
but it still doesn't allow me to do any sort of edits to the values of the range.
This is something I've tried to do, with the same range but a different function:
@xl_func
def iter(add): #When I changed line 4 to .extend([add]) I also changed 'add' to '[add]'
list = ["item_0"]
list.append(add) #I also tried .extend(add) and .extend([add]) but got the same error
list = [item + '_a' for item in list] #adds '_a' to the end of every item in 'list'
return list #returns the edited 'list'
What the Excel formula looks like:
=iter(A1:C4)
This function (iter(add)
) is what is returning the TypeError. funky(add)
does not return this error.
Okay, so I solved my own question by looking around for some better solutions, and I found one that helped a lot after a little bit of messing around with it.
I dissolved add
into a single big list using merged = list(itertools.chain.from_iterable(add))
(Credit: https://stackoverflow.com/a/953097/21975226)
Then everything worked as intended!
My main problem was that I was trying to add a string to the end of a list object, which is why it was returning the TypeError
.
What I did to fix that was dissolve the input list (add
) and use .extend()
to add it to list
(which I renamed to list_0
because of conflict with list(itertools.chain.from_iterable(add))
).
Then the line that adds the string _a
to the end of every element in list_0
worked perfectly!