Home>

There is a list. When trying to convert it to a single list with n-element nested lists, method next (chuks ()) -two times returns the first n elements, but when we use list (chunks ()) returns the correct result (list with nested lists of 10 elements) Why does calling a function with yield via list () return the full list and not the first 10 elements? I can't get to this on my own ... How exactly is the list formed at the end, when calling list (chunks (list_int, 10)) ?

list_int= [i for i in range (0, 100, 2)]
def chunks (lst, n):
    for i in range (0, len (lst), n):
         yield lst [i: i + n]
next (chunks (list_int, 10))
next (chunks (list_int, 10)) # the second call returns the same result
list (chunks (list_int, 10)) # returns the correct result /[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [20, 22, 24, 26, 28, 30, 32, 34, 36, 38], [40, 42, 44, 46, 48, 50, 52, 54, 56, 58], [60, 62, 64, 66, 68, 70, 72, 74, 76, 78], [80, 82, 84, 86, 88, 90, 92, 94, 96, 98]]

In short, in the next (chunks (...)) lines, you create a new generator each time and take the first element from it. Save the generator to the variable ch= chunks (...) and then take next (ch) from it. then it will iterate over the elements (which, in fact, list does internally).

GrAnd2021-10-04 09:07:35
  • Answer # 1

    in the documentation it says that the constructorlisttakes an argument supporting an iterator or an iterator object, hence the result you want.

    is roughly the same as:

    list_int= [i for i in range (0, 100, 2)]
    n= 10
    def chunks (lst, n):
        for i in range (0, len (lst), n):
             yield lst [i: i + n]
    chunk= chunks (list_int, n)
    res= [next (chunk) for _ in range (len (list_int) //n)]
    # or so res= [i for i in chunk]
    

    output:

    [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
     [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
     [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
     [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
     [80, 82, 84, 86, 88, 90, 92, 94, 96, 98]]
    
  • Answer # 2

    in the documentation it says that the constructorlisttakes an argument supporting an iterator or an iterator object, hence the result you want.

    is roughly the same as:

    list_int= [i for i in range (0, 100, 2)]
    n= 10
    def chunks (lst, n):
        for i in range (0, len (lst), n):
             yield lst [i: i + n]
    chunk= chunks (list_int, n)
    res= [next (chunk) for _ in range (len (list_int) //n)]
    # or so res= [i for i in chunk]
    

    output:

    [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
     [20, 22, 24, 26, 28, 30, 32, 34, 36, 38],
     [40, 42, 44, 46, 48, 50, 52, 54, 56, 58],
     [60, 62, 64, 66, 68, 70, 72, 74, 76, 78],
     [80, 82, 84, 86, 88, 90, 92, 94, 96, 98]]