When programming in Python, the list is the main (and really powerful) data structure that you use. Many times you come across a function that takes in a bunch of data, and returns a list of some values. Almost all of these many times, you want to apply the aforementioned function to a list of bunch of data. 

For example, you have a directory with quite many files (e.g. logs or results of experiments) and you want to parse each one of them with a function that returns a list of N values, e.g. [X1, X2, X3, …., XN]. After processing all the files, you want to store the N values in N different variables. Let’s use N=3 from now on, but the same process can be applied for any N.

To do the above, you have the following options: 

  1. Declare the three variables before a loop as lists. Do a for-loop over all files, and for each iteration use the function and append the returned values to each of the three lists. E.g.:
    a, b, c = [], [], []
    for a_file in get_all_files(form_this_dir): tmp_a, tmp_b, tmp_c = process_file(a_file)
    a.append(tmp_a) b.append(tmp_b) c.append(tmp_c)

     

     

  2. Or, you can do all the above in one line by using a list disentangling as:
    a, b, c = zip(*[process_file(a_file) for a_file in get_all_files(from_this_dir)])

 

A concrete example is:

the_list = [list(range(0, 3)), list(range(3, 6)), list(range(6, 9))]
a, b, c = zip(*the_list)

print(f'a is: {a}\nb is: {b}\nc is: {c}')
a is: (0, 3, 6) b is: (1, 4, 7) c is: (2, 5, 8)

Enoy!