Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join segments of a list

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.

like image 857
CheeseBuns Avatar asked Dec 02 '25 09:12

CheeseBuns


1 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))
like image 54
Peter Mason Avatar answered Dec 07 '25 03:12

Peter Mason