Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List or Tuple for throwaway iterables

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading