Search code examples
pythonlistfor-looplist-comprehension

list comprehension with double loops


I am a newbie in programming. I have a problem with a list comprehension. I need divide a list in tuple with size 5, and my code works well, but if I have an input of a list of lists, I don't know how insert a double loop in list comprehension. I hope that someone can help me. this is my code:

big_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
x = 5
bot = [tuple(big_list1[i: i + x])for i in range(0, len(big_list1), x)]

and this is output:

 bot=[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)]

But if I have a list of lists like this:

 my_list=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]

I would like to have this:

res=[[(1, 2, 3, 4, 5),(6, 7, 8, 9, 10),(11, 12, 13, 14, 15)], [(1, 2, 3, 4, 5),(6, 7, 8, 9, 10)], [(1, 2, 3, 4, 5)]]

I am confused because having "range" in the loop, I don't know how to do the nested loop.


Solution

  • define as a function:

    def split_in_tuples(input_list, tuple_length):
        return [tuple(input_list[i: i + tuple_length]) for i in range(0, len(input_list), tuple_length)]
    

    which you can then use like:

    big_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    split_in_tuples(big_list1, 5)
    

    gives

    [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)]
    

    then for your list of lists you can:

    my_list=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
    [split_in_tuples(sublist, 5) for sublist in my_list]
    

    which gives:

    [[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)], [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)], [(1, 2, 3, 4, 5)]]