I have created a function which returns a list
def GetAddressContainer(obj,obj1):
mylist = list()
for i in test['adresss']:
addresscotainer = i[id]
return mylist(addresscontainer)
When i call the function -
UkContainer = GetAddressContainer(Postcode,Country)
i get the following error message:
TypeError: 'list' object is not callable in python
Any ideas why i am getting this error and what i would have to update?
The problems seem to be in
return mylist(addresscontainer)
You using parentheses on the list and therefore calling it as a function, that's why you get the error. Without any more code I not entirely sure what to replace it with though.
Issues
The line mylist = list() basically creates an empty list which you can use to store any values. In the code mylist is being called (using (...)) which does not make sense in python since mylist is not a function.
Another issue with the code is that the value of addresscontainer is never being inserted into mylist.
Possible Solutions
So, as per your problem, either of the following solutions can be used:
Append addresscontainer into mylist iteratively within the for loop:
for i in test['adress']:
addresscontainer = i[id]
mylist.append(addresscontainer) # Inserts the value at the end of list
return mylist # Returns the list
[RECOMMENDED] Use list comprehension:
def GetAddressContainer(...):
return [i[id] for i in test['adress']] # Build list using "List Comprehension"
Replace mylist(addresscontainer) with list(addresscontainer) code.
Only list word could be a callable function because it defines a class of any list. And mylist = list() will be an instance of an abstract list, then, not callable.
change mylist = list() to mylist = []
it will create an empty list instead of a list object.
and you are not appending anything to the list.
Related
I have an array in my python program called ageArray. It contains the same attribute from each object in a group. Here's the intitialisation code:
ageArray = [[amoeba.age] for amoeba in amoebas]
Because the I want the attribute to change, I intitialise it at the start of a while statement. After this I have the following two lines of code:
for amoeba in amoebas:
amoeba.age = amoeba.age + 1
This is intended to add 1 to each age attribute, which will then be copied over to the ageArray the next time the while loop is iterated.
The use for this array is to add an extra requirement when two of the amoeba(objects) collide, as well as checking their x and y coords, I use this:
if ageArray[i] >= 10 and ageArray[h] <= 10:
This code is intended to make sure that the ages of the amoebae are more than 10 (the reason for this is complex and so I won't explain). For some reason this piece of code is throwing up this error:
TypeError: '>' not supported between instances of 'list' and 'int'.
Furthermore, is my code for adding 1 to each amoeba.age attribute correct? Tried using lambda with agearray but couldn't get it to work.
You create a list with List Comprehensions, where each element is a list with one element ([amoeba.age] is a list with a single element):
ageArray = [[amoeba.age] for amoeba in amoebas]
Just leave out the inner square brackets to create a list:
ageArray = [amoeba.age for amoeba in amoebas]
Initialise your list like this:
ageArray = [amoeba.age for amoeba in amoebas]
The way you are initialising is, creating a list of lists, that's why it is giving that type error.
I've created a blank list and am attempting to add a boolean to that list. However, I'm getting a few different errors. I'm fairly new to Python so any explanations would be helpful.
What I'm attempting to do is:
new_list=[]
new_list[0] = True #ERROR: TypeError: 'type' object does not support item assignment
or
new_list=[]
new_list.append(True) #ERROR: TypeError: descriptor 'append' requires a 'list' object but received a 'bool'
More precisely, I'm attempting to send this through a loop
new_list=[]
for arg in args:
if (arg == 'foo' or arg == 'bar'):
new_list[arg] = True
Obviously, the error in the first block is because the list is not accepting the boolean that's being passed. The second is also providing a similar error. However, because this is a blank list, shouldn't this accept any input?
I've attempted to follow this however, it looks like even this may not work.
Thanks in advance.
new_list = [] creates an empty list. In your first try, you are trying to access new_list[0], but the first place in the list ([0]) does not exist, because the list is empty.
When you want to add values to the list you need to use append. So your second try is correct, you should use: new_list.append(True), but the first line where you define the empty list is wrong. You used new_list[] instead of new_list = [].
As for the usage of new_list[], it's a syntax error. If you want to define an empty list you should use new_list = [] or new_list = list().
If you want to track the name of the arg if it is either "bar" or "foo", you could try something like this:
list = []
for arg in args:
if arg == 'foo' or arg == 'bar':
argDic = { arg: True }
list.append(argDic)
print(list)
# [{'foo': True}, {'bar': True}]
new_list = [] #creates a new list
new_bool_list = [True]*10 # creates a list size 10 of booleans
In python you don't have to set the size of the list, you can create an empty list and add onto it.
new_list = []
new_list.append(True)
print(new_list)
--------------
output:
[True]
for your loop question it depends on your arguments. new_list[arg] = True is generally how you set a value in a dictionary (HashMap in other languages). I think you'd be better off researching those for your intended question.
I am creating a dictionary of lists using integers as key in python. However the following code gives me t is None.
t = y.get("1",[]).append(1)
(But when I do counter[c] = counter.get(c,0) + 1, it will work.)
Can anyone help?
The reason why you are getting None for t with the append method is because append does not return a value. You can try this instead:
t = y.get("1",[])
t.append(1)
In web2py I have been trying to break down this list comprehension so I can do what I like with the categories it creates. Any ideas as to what this breaks down to?
def menu_rec(items):
return [(x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children)) for x in items or []]
In addition the following is what uses it:
response.menu = [(SPAN('Catalog', _class='highlighted'), False, '',
menu_rec(db(db.category).select().as_trees()) )]
So far I've come up with:
def menu_rec(items):
for x in items:
return x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children))
I've got other variations of this but, every variation only gives me back 1(one) category, when compared to the original that gives me all the categories.
Can anyone see where I'm messing this up at? Any and all help is appreciated, thank you.
A list comprehension builds a list by appending:
def menu_rec(items):
result = []
for x in items or []:
url = URL('shop', 'category', args=pretty_url(x.id, x.slug))
menu = menu_rec(x.children) # recursive call
result.append((x.title, None, url, menu))
return result
I've added two local variables to break up the long line somewhat, and to show how it recursively calls itself.
Your version returned directly out of the for loop, during the first iteration, and never built up a list.
You don't want to do return. Instead append to a list and then return the list:
def menu_rec(items):
result = []
for x in items:
result.append(x.title,None,URL('shop', 'category',args=pretty_url(x.id, x.slug)),menu_rec(x.children)))
return result
If you do return, it will return the value after only the first iteration. Instead, keep adding it to a list and then return that list at the end. This will ensure that your result list only gets returned when all the values have been added instead of just return one value.
I am doing the following :
recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
params = (record['value'],record['value2'],'31')
i am getting the error :
TypeError: 'function' object is not
subscriptable
what is wrong here ?
recordList=[lambda:defaultdict(str)]
creates a list with a function that returns defaultdict(str). So it's basically equivalent to:
def xy ():
return defaultdict(str)
recordList = []
recordList.append( xy )
As such, when you start your for loop, you get the first element from the list, which is not a list (as all the other elements you push to it), but a function. And a function does not have a index access methods (the ['value'] things).
recordList is a list with 1 element which is a function.
If you replace the first line with
recordList = []
the rest will wor.
you're adding a lambda to recordList, which is of type 'function'. in the for .. loop, you're trying to subscript it (record['value'], record['value2'], etc)
Initialize recordList to an empty list ([]) and it will work.