2

I have a function which returns 4 lists.

def foo ( Input1, input 2)
    return list1, list2, list3, list 4

I am using following code right now:

x0, y0, z0, w0 = foo(ip0, ip4)
x1, y1, z1, w1 = foo(ip3, ip1)
x2, y2, z2, w2 = foo(ip3, ip4)
x3, y3, z3, w3 = foo(ip1, ip2)

I want to reduce the number of lines and may be use a for loop.

I tried while loop:

i=0
while i<3:
    'x'+str(i), 'y'+str(i),'z'+str(i),'w'+str(i)= foo(input[i], input[i])
    i +=1

Python is throwing an error, it thinks I am assigning a value to a string. How do I unpack the tuple and generate variable name using a loop or automatically?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Just make a list of lists instead: ```{python} import itertools output = list(itertools.starmap(foo, [(ip0, ip4), (ip3, ip1), (ip3, ip4), (ip1, ip2)])) ``` will return a list, whose each element is four lists. Consider changing you variable names to something more meaningful and generating the tuples in a more systematic way. – xletmjm Feb 18 '20 at 23:21
  • In the line you have here: `'x'+str(i),'y'+str(i),'z'+str(i),'w'+str(i)= foo(input[i], input[i])` This is actually creating a tuple of strings on the left hand side of the equals sign. So you're ending up with something like ('x1', 'y1', 'z1', 'w1') = foo(input[i], input[i]). This means Python is trying to unpack the result of foo() into a tuple of strings. I understand what you're trying to do here, but I would suggest instead unpacking them into a list of tuples, rather than separate variables. – Aiden Blishen Cuneo Feb 18 '20 at 23:22

1 Answers1

1

You can do something like this:

def MyFunction(arg1, arg2):

    list1 = [arg1, arg2]
    list2 = [arg2, arg1]

    return list1, list2


# create empty dictionary:
my_dictionary = {}

# iterate in given range:
for index in range(4):

    # get output of function:
    list1, list2 = MyFunction(1, 2)

    # assign output to dictionary:
    single_dictionary_entry = {
        'x' + str(index) : list1,
        'y' + str(index) : list2,
    }

    # update original dictionary with new entry:
    my_dictionary.update(single_dictionary_entry)

# print result:
print(my_dictionary)
Daniel
  • 3,228
  • 1
  • 7
  • 23