I'm trying to make a function where you pass a list and an index and it returns another list that contains the element from the first list you passed to it that belongs to the place of the index you passed to it. I have written something like this:
def indextoentry(lista,index):
listresult = []
listresult = listresult + lista[index]
return(listresult)
As you may already know this gives a type mismatch error on the line listresult = listresult + lista[index]
So I try something else using the append() method:
def indextoentry(lista,index):
listresult = []
listresult = listresult.append(lista[index])
return(listresult)
This does not give me an error but it gives me 'None'
if I do>>> print(indextoentry([1,2,3],1))
How can I get my function to return a list? Thank you very much in advance.
In the first example you are adding a list and something else (int, float, str, etc) and that causes a type mismatch error. Solution:
In the second you are using the append() method wrong, what you do is:
Now
lisresult
it is not a list but the return of the append() method, which since it does not return anything is None. It is used like this:Simplifying you can do this:
Or alternatively:
This is because the method
append
of a list . does not return a value . that's why when doing the assignment, nothing is assigned to your variablelistresult