1

I have this nested list:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]

Count of sublist elements are always in mulitple of 3. I want to have 3 elments in each sublist. Desired output:

list_1 = [[1,2,3], [1,2,3], [4,5,6],[1,2,3], [4,5,6], [7,8,9]]

I can achieve this but first i have to flatten the list and then create the nested list. My code:

list_1 = [values for sub_list in lists_1 for values in sub_list]  # flatten it first

list_1 = [list_1[i:i+3] for i in range(0, len(list_1), 3)]

Is there a way to skip the flatten step and get the desired result?

3 Answers 3

4

You can use a nested list comprehension:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
result = [i[j:j+3] for i in list_1 for j in range(0, len(i), 3)]

Output:

[[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
Sign up to request clarification or add additional context in comments.

Comments

1

Here is how you can use nested list comprehensions:

list_1 = [[1,2,3],[1,2,3,4,5,6],[1,2,3,4,5,6,7,8,9]]

list_1 = [a for b in list_1 for a in b]
list_1 = [list_1[i:i+3] for i in range(0,len(list_1),3)]

print(list_1)

Output:

[[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

Comments

0

To put my two cents in, you could use two generator functions, one that flattens the list (with an arbitrarly nested list) and one that yields pairs of n values:

def recursive_yield(my_list):
    for item in my_list:
        if isinstance(item, list):
            yield from recursive_yield(item)
        else:
            yield item

def taken(gen, number = 3):
    buffer = []
    for item in gen:
        if len(buffer) < number:
            buffer.append(item)
        else:
            yield buffer
            buffer = []
            buffer.append(item)
    if buffer:
        yield buffer
    
result = [x for x in taken(recursive_yield(list_1))]

Here are some examples of the in- / outputs:

list_1 = [[1,2,3], [1,2,3,4,5,6], [1,2,3,4,5,6,7,8,9]]
# -> [[1, 2, 3], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

list_1 = [1,2,3,4,5,6]
# -> [[1, 2, 3], [4, 5, 6]]

list_1 = [1,2,[[1,2,4,5], [[[[1,10,9]]]]]]
# -> number = 5
# -> [[1, 2, 1, 2, 4], [5, 1, 10, 9]]

Thus, the solution is much more flexible than slicing alone.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.