Certain Python builtins, such as any
and all
, require an iterable argument. A common pattern I encounter with these is that I chain creating the iterable with the function call. For example:
locations = ["foo", "bar", "baz"]
if any(["city" in location for location in locations]):
print("Locations includes a city")
Is there any benefit to doing this with a tuple instead...
locations = ["foo", "bar", "baz"]
if any(("city" in location for location in locations)):
print("Locations includes a city")
...in terms of memory usage or execution time?
CodePudding user response:
That's not a tuple; it's a generator expression. And there is a very big benefit: the generator expression only produces values as any
requests them, while the list comprehension has to produce a full list of values before any
can start iterating over it. Consider the following:
if any(["city" in location for location in ["city", "country", "county", "state"]):
The list comprehension has to build [True, False, False, False]
before any
can start iterating, and of course the last three False
values are irrelevant, because any
will return as soon as it sees the first True
. Compare to
if any(("city" in location for location in ["city", "country", "county", "state"])):
in which case only "city" in "city"
will be computed before any
sees True
and returns, without every having to make the other three comparisons.
When the generator expression is the only argument to a function, you can omit the surrounding parentheses:
if any("city" in location for location in locations):