How to join segments of a list

Viewed 118

I have found different answers elsewhere that will work, but I can't quite figure out why my code is not working properly. What I am trying to do is take a list of alphabetical characters and join the first 4, second 4, third 4, etc. elements. I'll paste an example below to make this more clear.

If given the following list: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'I', 'M', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

I want to combine the elements so that I receive the following output:

['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']

I thought I identified a good solution on my own, but it doesn't seem to work. What I tried was:

x = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
y = 4

def wrap(string, max_width):
    slist = [char for char in string]
    new = []
    for i in range(0, len(slist), max_width):
        new.append(''.join(slist[i:max_width]))
    return new

wrap(x, y)

The output that I get from this is:

['ABCD', '', '', '', '', '', '']

I would appreciate if if someone could help me identify what is wrong and help me fix it. Like I said previously, I have found other answers online that will do what I want, but I really want to figure out where I went wrong here.

2 Answers

It looks like there was logic issues in the for loop:

You were trying to add items between i:max_width. However max_width is always 4 and when i is > 4 you get no items return as it is an empty string. Instead I have added max_width to meaning the grouping is always the same size:

x = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
y = 4

def wrap(string, max_width):
    slist = [char for char in string]
    new = []
    for i in range(0,len(slist),max_width):
        new.append(''.join(slist[i:(i+max_width)]))
    return new

print(wrap(x, y))

Those earlier posts from @Peter Mason working fine as it just modified 'minimally' original code. However, the original code can be improved further to save a few steps: (the slist = .... is redundant, as string is a character sequence and can be directly index-access)


    >>> s = uppers = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
    >>> max_width = 4
    >>> newStr = []
    >>> for i in range(0, len(s), max_width):
        newStr.append(''.join(s[i:i+4]))
    
        
    >>> newStr
    ['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
    >>> 

   Or, list comprehension:

         def wrap(string, max_width):
            return [''.join(string[i:i+max_width]) 
                            for i in range(0, len(string), max_width)]
        
        >>> wrap(s, 4)
        ['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
        >>> 
Related