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
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)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With