Search code examples
pythonlistfunctiontuplesiterable-unpacking

Get a list with tuple unpacking in a function


I have a given function that takes different inputs (example):

def myfunction(x, y, z):
    a = x,y,z
    return a

Then, this for loop:

tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
    lst.append(myfunction(*tripple))
lst

Which works like this:

[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]

I want to run it for i in range(n) and get a list of lists as an output,

for i in range(3):
    for tripple in tripples:
        lst_lst.append(myfunction(*tripple))
lst_lst

Output:

[('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm'),
 ('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm'),
 ('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')]

Desired output:

[[('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')],
 [('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')],
 [('a', 'b', 'c'),
 ('d', 'e', 'f'),
 ('g', 'h', 'i'),
 ('j', 'k', 'm')]]

If it helps of something, full code:

def myfunction(x, y, z):
    a = x,y,z
    return a

lst = []
lst_lst = []
tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
for tripple in tripples:
    lst.append(myfunction(*tripple))
for i in range(3):
    for tripple in tripples:
        lst_lst.append(myfunction(*tripple))
lst_lst

Solution

  • def myfunction(x, y, z):
        a = x,y,z
        return a
    
    lst = []
    tripples = [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'm')]
    
    for i in range(3):
        lst_lst = []
        for tripple in tripples:
            lst_lst.append(myfunction(*tripple))
    
        lst.append(lst_lst)
    
    print(lst)