Home > Net >  Understanding list comprehension involving min function
Understanding list comprehension involving min function

Time:05-12

I am well-versed with list comprehension.

However, I am not able to understand the below statement:

min((-len(list), list[-1] - list[0]   1) for list in [[0, 4], [1, 2]])[1]

I only understand the portion for list in [[0, 4], [1, 2]] wherein we are iterating the list.

CodePudding user response:

So, list is going to be, in turn, [0,4], and [1,2]. For the first, the tuple is going to be (-2, 5) (5 == 4 - 0 1), for the second, the tuple is going to be (-2, 2) (2 == 2 - 1 1). The smallest of those is (-2,2), so that's what will be returned.

So, this is trying to find the longest sublists, and will return the smallest difference between the first element and the last element of the lists that size.

CodePudding user response:

It's equivalent to the following code snippet:

min((-len(list), list[-1] - list[0]   1) for list in [[0, 4], [1, 2]])[1]
newlist = list()
for list in [[0, 4], [1, 2]]:
    newlist.append((-len(list), list[-1] - list[0]   1))
min = min(newlist)
output = min[1]

  • Related