Write a list, dict and set comprehension for a realistic ops task.
BeginnerConceptLanguage essentials & functions
Answer
instances = [...] # from describe_instances
running_ids = [i["InstanceId"] for i in instances if i["State"]["Name"] == "running"]
tags_by_id = {i["InstanceId"]: {t["Key"]: t["Value"] for t in i.get("Tags", [])}
for i in instances}
instance_types = {i["InstanceType"] for i in instances}
Comprehensions are faster than an explicit append loop and read as "what" rather than "how". If one needs more than one if and one for, write a normal loop for readability.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner