Better way to split this list?

I was doing some of the courses for strings in python and I had to split a list of colors and add them to an empty list, I split them based on the symbol ‘&’, ex: lst = [white, white&blue, red, white&red&blue],
I did this just fine only to realize after I was finished that some items on the list had two ‘&’,

my question is how can I make python split items into lists with any amount of symbols without producing an index error, without just adding in an elif statement each time there is an extra ‘&’

my code:

thread_sold_split = []
for i in thread_sold:
    if i.find('&') > -1:
        x = i.split('&')
        if len(x) >= 3:
            thread_sold_split.append(x[0])
            thread_sold_split.append(x[1])
            thread_sold_split.append(x[2])
        elif len(x) < 3:
            thread_sold_split.append(x[0])
            thread_sold_split.append(x[1])
    else:
        thread_sold_split.append(i)

Thanks For The Help!

It sounds like you’re looking for .extend rather than .append which adds a sequence to a list, item by item. Just note that split will always return a list, even one with empty strings so you may just need to be a little careful about using it for datasets that aren’t clean. A quick example of extend-

a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
> [1, 2, 3, 4 ,5 6]
1 Like

Wow that makes things way easier, Thanks for the help!