I'm not able to add given list
Question:
**Not able to add the given list a
a = ['1','2','3','4','5','6']
def sums (a):
return sum(a)
print(sums(a))
gives me error unsupported operand type(s) for +: 'int' and 'str'
i understand that i can’t add list of str
implicitly without converting them to int
, but when i try to convert the list a
into int
a = ['1','2','3','4','5','6']
def sums (a):
int_a = int(a)
return sum(a)
print(sums(a))
it still gives me the error **
int() argument must be a string, a bytes-like object or a number, not 'list'
just a learner,
any help would be much appreciated!
Answers:
When you do
int_a = int(a)
The code tries to convert the list a
to an int. What you need to do is
def sums (a):
a = [int(x) for x in a]
return sum(a)
This converts each element in the list to an integer. You could cut this down even further to
def sums (a):
return sum(int(x) for x in a)
**Not able to add the given list a
a = ['1','2','3','4','5','6']
def sums (a):
return sum(a)
print(sums(a))
gives me error unsupported operand type(s) for +: 'int' and 'str'
i understand that i can’t add list of str
implicitly without converting them to int
, but when i try to convert the list a
into int
a = ['1','2','3','4','5','6']
def sums (a):
int_a = int(a)
return sum(a)
print(sums(a))
it still gives me the error **
int() argument must be a string, a bytes-like object or a number, not 'list'
just a learner,
any help would be much appreciated!
When you do
int_a = int(a)
The code tries to convert the list a
to an int. What you need to do is
def sums (a):
a = [int(x) for x in a]
return sum(a)
This converts each element in the list to an integer. You could cut this down even further to
def sums (a):
return sum(int(x) for x in a)