evens = []
for i in range(11):
if i % 2 == 0:
evens.append(i)
print(evens)
[0, 2, 4, 6, 8, 10]
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]
words = ['AARDVARK','APPLE','ARROW','BARN','CACTUS']
a_words = []
for word in words:
if word[0] == 'A':
a_words.append(word)
print(a_words)
['AARDVARK', 'APPLE', 'ARROW']
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:
evens = [i for i in range(11) if i % 2 == 0]
print(evens)
[0, 2, 4, 6, 8, 10]
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:
squares = [i**2 for i in range(10) if i % 2 == 0]
print(squares)
[0, 4, 16, 36, 64]
Try to write the list comprehension corresponding to our A words example.