Question about syntax of algorithm

I’ve seen this type of algorithm a lot recently:

return all(i in range(1000) and abs(i - j) >= 10 for i in li for j in li if i != j) and len(set(li)) == 100

It writes return first and begins the for…in loop halfway through.
I’ve this alot and it seems to be preferable. Why? Is is quicker? Cleaner?

It’s called a “comprehension”.

You can learn more about it here: Python - List Comprehension

I’d recommend staying away from complicated ones like this.

A more readable and reusable approach might be something like this.

Create some filters using anonymous functions

len_100_filter = lambda x: len(x) == 100
contains_55 = lambda x:  55 in x

Filter lists using comprehension

list1 = list(range(100))
list2 = list(range(101))
list3 = list(range(101))
list4 = list(range(99))

dict_of_lists = {"list1": list1, "list2":  list2, "list3":  list3, "list4": list4}
filtered_dict_of_lists = [label for label, list in dict_of_lists.items() if (len_100_filter(list) and contains_55(list))]


# Output:
# ['list1', 'list2']

You could even have a utility file where you import filters you want to use if they get complicated and come up again and again.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.