0

I am trying to slice a list into a list of lists, whereby the original list is sliced at the point where a string type object is detected e.g.

array = ['Hello',1,2,3,'Goodbye',4,6,'Bye',7,8,9,5]

to

new_array = [['Hello',1,2,3],['Goodbye',4,6],['Bye',7,8,9,5]]

How could this be achieved?

1 Answer 1

0

You can use a generator function for this, e.g.:

def gen(arr):
    r = []
    for el in arr:
        if r and isinstance(el, str):
            yield r
            r = []
        r.append(el)
    if r:
        yield r

>>> list(gen(array))
[['Hello', 1, 2, 3], ['Goodbye', 4, 6], ['Bye', 7, 8, 9, 5]]
Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks so much! That's really interesting. I've never come across generator functions before. Do you have a good website that you'd recommend that discusses them?
The official docs should get you a long part of the way: docs.python.org/3/howto/functional.html#generators

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.