Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list into tuple then add this tuple into list in python

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

like image 429
Reboot Avatar asked Oct 06 '26 22:10

Reboot


2 Answers

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)]
like image 143
Eugene Yarmash Avatar answered Oct 09 '26 12:10

Eugene Yarmash


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]
like image 40
jDo Avatar answered Oct 09 '26 10:10

jDo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!