0

I am having difficulty with one of my homework questions.

Basically, I am to create a function using a for loop to count the characters used in strings which are inside of a list. I am able to get the length of the strings with len(), but I can only get one of the strings and I can't seem to get it in list form.

My Code:

def method1(input1):

    total = 0

    a = []

    for word in input1:

        total = len(word)

        a = [total]

    return a

This returns [3] with the input ['seven', 'one']

Any help would be appreciated. I am very new to Python.

3
  • return sum([len(a) for a in input1]) Commented Sep 15, 2017 at 2:48
  • all you need to do is a += [total] . this returns the length of strings in a list form. So if your input is ['Seven', 'one']. It will return ` [5,3]` Commented Sep 15, 2017 at 2:52
  • @Digvijayad That did the trick! Thank you so much! Commented Sep 15, 2017 at 3:17

1 Answer 1

2

Well here is one way of doing it. You have list "a" with different strings inside of them. You can simply iterate through the list counting the length of each string.

def method1(input1):

    l = list(input1)
    total = sum(len(i) for i in l)
    return int(total)

print(method1(["hello", "bye"]))

What you are doing here is receiving an input and converting it to a list. Then for each value inside of the list, you are calculating it's length. The sum adds up those lengths and finally, you return total.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need int(total) it is already an int. You also don't need l - for i in input1 would be sufficient - this just boils down to return sum(len(i) for i in input1) or return sum(map(len, input1))
Thanks for the feedback!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.