2

Hi I want my output to be

add_sizes(['hello', 'world']) -> [('hello', 5), ('world', 5)]

but I'm getting

add_sizes(['hello', 'world']) -> [('hello', 5), ('hello', 5, 'helloworld', 5)]

My code is

def add_sizes(strings):

    s = ()
    t=[]
    m=[]
    for i in strings:
        x=i
        for i,c in enumerate(list(x)):
            t.append(c)
        l=(str(''.join(t)),i+1)
        s += l
        m.append(s)
    print(m)

Any suggestion would be appreciated thanks

2
  • I think you're over-complicating it a bit. You just need tuples containing every string in strings along with the len() of the string. Append these, one by one, to a list and return/print the list when you're done. Your enumerate and l=(str(''.join(t)),i+1) statements aren't necessary Commented Apr 7, 2016 at 23:46
  • The cause of your issue is where you have s=();t=[] (should be inside the loop) but as eugene y says, the better solution is a list comprehension. Commented Apr 7, 2016 at 23:47

2 Answers 2

8

Just use a list comprehension:

>>> def add_sizes(strings):
...     return [(s, len(s)) for s in strings]
... 
>>> 
>>> add_sizes(['hello', 'world'])
[('hello', 5), ('world', 5)]

Or if you want to do it in-place:

>>> def add_size(strings):
...     for i, s in enumerate(strings):
...         strings[i] = (s, len(s))
...     return strings
... 
>>> add_sizes(['hello', 'world'])
[('hello', 5), ('world', 5)]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it works like a charm, I didn't know that we can do it this way. much appreciated!
1

Someone already gave a complete solution so I'll just post mine too:

def add_sizes(strings):
    l = []
    for string in strings:
        l.append((string, len(string)))
    return l

def add_sizes(strings):
    return [(s, len(s)) for s in strings]

Comments

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.