<jupyter_start><jupyter_text>Comprehensions  The list comprehension If you write a for loop **inside** a pair of square brackets for a list, you magic up a list as defined.This can make for concise but hard to read code, so be careful.<jupyter_code>[2**x for x in range(10)]<jupyter_output><empty_output><jupyter_text>Which is equivalent to the following code without using comprehensions:<jupyter_code>result = []
for x in range(10):
    result.append(2**x)
    
result<jupyter_output><empty_output><jupyter_text>You can do quite weird and cool things with comprehensions:<jupyter_code>[len(str(2**x)) for x in range(10)]<jupyter_output><empty_output><jupyter_text>Selection in comprehensions You can write an `if` statement in comprehensions too:<jupyter_code>[2**x for x in range(30) if x%3 == 0]<jupyter_output><empty_output><jupyter_text>Consider the following, and make sure you understand why it works:<jupyter_code>"".join([letter for letter in "<NAME>" 
         if letter.lower() not in 'aeiou'])<jupyter_output><empty_output><jupyter_text>Comprehensions versus building lists with `append`: This code:<jupyter_code>result = []
for x in range(30):
    if x%3 == 0:
        result.append(2**x)
result<jupyter_output><empty_output><jupyter_text>Does the same as the comprehension above. The comprehension is generally considered more readable. Comprehensions are therefore an example of what we call 'syntactic sugar': they do not increase the capabilities of the language. Instead, they make it possible to write the same thing in a more readable way.  Almost everything we learn from now on will be either syntactic sugar or interaction with something other than idealised memory, such as a storage device or the internet. Once you have variables, conditionality, and branching, your language can do anything. (And this can be proved.)  Nested comprehensions If you write two `for` statements in a comprehension, you get a single array generated over all the pairs:<jupyter_code>[x - y for x in range(4) for y in range(4)]<jupyter_output><empty_output><jupyter_text>You can select on either, or on some combination:<jupyter_code>[x - y for x in range(4) for y in range(4) if x >= y]<jupyter_output><empty_output><jupyter_text>If you want something more like a matrix, you need to do *two nested* comprehensions!<jupyter_code>[[x - y for x in range(4)] for y in range(4)]<jupyter_output><empty_output><jupyter_text>Note the subtly different square brackets. Note that the list order for multiple or nested comprehensions can be confusing:<jupyter_code>[x+y for x in ['a','b','c'] for y in ['1','2','3']]
[[x+y for x in ['a','b','c']] for y in ['1','2','3']]<jupyter_output><empty_output><jupyter_text>Dictionary Comprehensions You can automatically build dictionaries, by using a list comprehension syntax, but with curly brackets and a colon:<jupyter_code>{(str(x))*3: x for x in range(3)}<jupyter_output><empty_output><jupyter_text>List-based thinking Once you start to get comfortable with comprehensions, you find yourself working with containers, nested groups of lists and dictionaries, as the 'things' in your program, not individual variables.  Given a way to analyse some dataset, we'll find ourselves writing stuff like:    analysed_data = [analyze(datum) for datum in data] There are lots of built-in methods that provide actions on lists as a whole:<jupyter_code>any([True, False, True])
all([True, False, True])
max([1, 2, 3])
sum([1, 2, 3])<jupyter_output><empty_output><jupyter_text>My favourite is `map`, which, similar to a list comprehension, applies one function to every member of a list:<jupyter_code>[str(x) for x in range(10)]
list(map(str, range(10)))<jupyter_output><empty_output><jupyter_text>So I can write:        analysed_data = map(analyse, data)We'll learn more about `map` and similar functions when we discuss functional programming later in the course.  Classroom Exercise: Occupancy Dictionary Take your maze data structure. First write an expression to print out a new dictionary, which holds, for each room, that room's capacity. The output should look like:<jupyter_code>{'bedroom': 1, 'garden': 3, 'kitchen': 1, 'living': 2}<jupyter_output><empty_output><jupyter_text>Now, write a program to print out a new dictionary, which gives,for each room's name, the number of people in it. Don't add in a zero value in the dictionary for empty rooms. The output should look similar to:<jupyter_code>{'garden': 1, 'living': 1}<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09699666295884316, 'fraction_numerical': 0.010901001112347052, 'mean_word_length': 6.125198098256735, 'pattern_counts': {'":': 0, '<': 62, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '105029', 'license': 'CC-BY-3.0', 'n_tokens_mistral': 1405, 'n_tokens_neox': 1336, 'n_words': 548, 'path': 'ch00python/037comprehensions.ipynb', 'repo_name': 'andyyhchen/rsd-engineeringcourse', 'size': '4507'}