-1

**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!

khelwood
  • 52,115
  • 13
  • 74
  • 94
Shivam
  • 29
  • 6

1 Answers1

2

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)
CDJB
  • 13,204
  • 5
  • 27
  • 47
  • so, i can't convert whole list at once and i have to iterate every string one by one? – Shivam Dec 12 '19 at 11:16
  • 1
    @Shivam you could also use [`map()`](https://docs.python.org/3/library/functions.html#map); `list(map(int, a))` gives you a list of integers. – CDJB Dec 12 '19 at 11:17
  • @Shivam no you cannot "convert the whole list at once", because your list may contain things that cannot be converted to ints and Python has no way to know what it should do with those - only you can tell. – bruno desthuilliers Dec 12 '19 at 11:28