#!/usr/bin/env python # coding: utf-8 # # Module 2 # # ## Video 7: Generating Lists # **Python for the Energy Industry** # # It's common to make a list by conditionally appending inside a loop. See this example of making a list of even numbers: # In[1]: evens = [] for i in range(11): if i % 2 == 0: evens.append(i) print(evens) # Here's another example, of finding the words in a list beginning with A: # # *Note: strings can be treated in many ways as a list of characters - see below how we access the first letter of word as word[0]* # In[2]: words = ['AARDVARK','APPLE','ARROW','BARN','CACTUS'] a_words = [] for word in words: if word[0] == 'A': a_words.append(word) print(a_words) # This procedure is so common that there is a Python shorthand for it, called the 'list comprehension' which takes the form: # # ``` new_list = [item for item in old_list if condition] ``` # # Here's how this looks for our even numbers example: # In[3]: evens = [i for i in range(11) if i % 2 == 0] print(evens) # You can also apply a function onto the item before storing it in the list. We will cover functions in more detail later, but here is a simple example: # In[5]: squares = [i**2 for i in range(10) if i % 2 == 0] print(squares) # ### Exercise # # Try to write the list comprehension corresponding to our A words example. # In[ ]: