How to cut a list by specific item?

You get the error because you assign the result of the list.append() function - which is None - to up in

up, down = up.append(down[: (down.index("b") + 1)]), down[...snipp...] 
#          ^^^^^^^^ returns None

list.append is a "in-place" operation that returns None so up is going to be None in the next iteration.

Keeping closest to what you got you could use

down = ["a", "b", "c", "d", "b", "e", "r"]
up = []
while 'b' in down:
    b_index = down.index('b') + 1
    up.append(down[:b_index])
    down = down[b_index:]
up.append(down)

but simply iterating your original and assembling the sublists in a second list is cleaner in my opinion:

k = ["a", "b", "c", "d", "b", "e", "r"]

result = [[]]
for e in k:
    if e != "b":
        result[-1].append(e)
    else:
        result[-1].append(e)
        result.append([])

if result[-1] == []: 
    result.pop() # thx iBug's comment

print(result) # [['a', 'b'], ['c', 'd', 'b'], ['e', 'r']]

I think that is much clearer then what your code tries to do - your "what I want ["a", "b"]["c", "d", "b"] ["e", "r"]" is not valid python.


A slightly different version of the code would be:

k = ["a", "b", "c", "d", "b", "e", "r"]
b = []
while True:
    try:
        b_idx = k.index("b")
    except: 
        b.append(k)
        break
    else:
        b,k = b+[k[:b_idx+1]],k[b_idx+1:]
print(b) 

But you need far mor searches into your list via .index() and try: except so it has a worse performance then simply iterating the list once.

Tags:

Python

List