+ 3

whats the use of square brackets in the list "all" and "any" function calls?

examples below for reference. i have run the code with and without them and still get the same results so it doesn't make sense to me at all. #list functions #all function used to make comparisons through array like objects and returns true if the comparison is true for all items in the array and false if otherwise. tuple1=(67,89,34,76,90,100) if all(x<105 for x in tuple1): print("all values are greater than 105") else: print("All values are less than 105") #any function is used to make comparison through array like objects and returns true if the comparison is true for any of the items in the object else its false. dict1={"kampala":"kampala", 4:"wakiso", 9:"Mpigi", 10:"Gulu"} #note for dictionaries, it compares the keys not values. if any(x=="kampala" for x in dict1): print("we have our capital city") else: print("we dont have out caiptal city here")

28th Dec 2018, 5:49 AM
Kalyx Moses
Kalyx Moses - avatar
3 ответов
+ 4
[2/2] Apart from time, we also save space using a generator expression. The whole list has to be stored somewhere internally in the first example. The generator just evaluates them one by one, and takes minimal space. This was a specialized example; not every case will have this much gain in speed. The story is essentially the same with any(). Hope that helps 😊 Code: https://code.sololearn.com/cB8SHSFH0Lfr/?ref=app
28th Dec 2018, 7:58 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
[1/2] I'll start with a test code to compare speeds: from timeit import timeit def a(): if all([x>0 for x in range(10000)]): pass def b(): if all(x>0 for x in range(10000)): pass print("With brackets:", timeit(a, number=100)) print("Without brackets:", timeit(b, number=100)) Why is the second one significantly faster? The one with brackets makes a list using list comprehension. So it checks if each x in range(1000) is greater than 0, and thus creates a list with one False at index 0, and True in the following positions. *Then* it feeds it to the all() function. The one without brackets creates a generator expression. It doesn't make those checks immediately. It evaluates them only when called for. Now all() stops whenever it finds a "False" in the iterator and returns False. So in the second case, we only end up evaluating the first expression (0>0). But in the first one we spent too much time making all those redundant evaluations when we only needed just one.
28th Dec 2018, 7:57 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
'all' and 'any' just take any iterable (or an expression that generates one on the fly). Can be a string, a tuple, a list - and also a generator. Without brackets you're creating a generator (operating like Kishalaya Saha explained), with brackets you're creating a list.
28th Dec 2018, 3:45 PM
HonFu
HonFu - avatar