I can't add an int to a list
-
21-12-2019 - |
Question
list == []
def MultiplesNumber(a):
for i in range(1, a+1):
if a % i == 0:
return i
list.append(MultiplesNumber(100))
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
I can't add i
to list
, any idea?
Solution
Two things are wrong with your code:
- You are doing a
list == []
which returns a True or False since==
is a comparison operator. In this case it returnsFalse
. You need to use=
to initialize a variable. list
is the name of a built-in type in python, use something else as your variable name.
Fixing both of them :
alist = []
def MultiplesNumber(a):
for i in range(1, a+1):
if a % i == 0:
return i
alist.append(MultiplesNumber(100))
gives the correct output.
OTHER TIPS
list
is the inbuilt keyword which shadows your list
variable. You need to assign a list to a variable not check its equality.
lst = []
def MultiplesNumber(a):
return [x for x in range(1, a + 1) if a % 2 == 0]
lst.append(MultiplesNumber(100))
print(lst)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow