Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the code zip( *sorted( zip(units, errors) ) ) do?

Tags:

python

For my application units and errors are always lists of numerical values. I tried googling what each part does and figured out the firs part of zip. It seems

   ziped_list = zip(units, errors)

simply pairs the units and errors to produce a list as [...,(unit, error),...]. Then Its passed to sorted which sorts the elements. Since I did not provide the argument for key, then it compares the elements directly as the documentation implies:

The default value is None (compare the elements directly).

Since the ziped_list is a list of tuples of integers, then it seems that it makes a comparison between tuples directly. From a small example in my terminal (python 3) it seems it compares based on the first element (even though the documentation implies the comparison is element wise):

>>> (1,None) < (2,None)
True
>>> (2,None) < (1,None)
False

The last bit the unpacking and then zip still remain a mystery and I have not been able to figure out what they do. I understand that * unpacks to positional argument but doing * doesn't let me see exactly what its doing if I try it in the command line. What further confuses me is why zip requires to be passed as argument an unpacked list such as *sorted if it already takes as an argument zip(*iterable) a variable called iterable. It just seems confusing (to me) why we would need to unpack something that just allows as input a list of iterables.

like image 785
Charlie Parker Avatar asked Feb 07 '23 02:02

Charlie Parker


2 Answers

If you don't unpack list, then pass to argument as one element, so zip can't aggregates elements from each of the iterables. For example:

a = [3, 2, 1,]
b = ['a', 'b', 'c']
ret = zip(a, b)
the_list = sorted(ret)  
the_list >> [(1, 'c'), (2, 'b'), (3, 'a')]

zip(*the_list) is equal to zip((1, 'c'), (2, 'b'), (3, 'a'))

output : [(1, 2, 3), ('c', 'b', 'a')]

If you just use zip(the_list) is equal to zip([(1, 'c'), (2, 'b'), (3, 'a')],)

output: [((1, 'c'),), ((2, 'b'),), ((3, 'a'),)]

You can also see What does ** (double star) and * (star) do for Python parameters?

like image 140
Em L Avatar answered Feb 08 '23 16:02

Em L


Seems you've already figured out what zip does.

When you sort the zipped list, sorted compares the first element of each tuple, and sorts the list. If the first elements are equal, the order is determined by the second element.

The * operator then unpacks the sorted list.

Finally, the second zip recombines the the output.

So what you end up with is two lists of tuples. The first list is errors, sorted from smallest to largest. The second list is the corresponding errors.

like image 26
Batman Avatar answered Feb 08 '23 15:02

Batman