For Loop
number = [1, 2, 3]
new_list = []
for n in numbers:
add_1 = n + 1
new_list.append(add_1)
List Comprehension
- We will create the name of the new list and instead of creating an empty list and then having to append to it or populate it, we actually going to create it straight in the same line.
- So we open up a set of square brackets to denote that we're creating a new list, and then we have this new _item for item in list keyword pattern.
#Keyword Method
new_list = [new_item for item in list]
numbers = [1, 2, 3]
new_list = [n+1 for n in numbers]
-------
new_list = [2, 3, 4]
- Now it's important to remember that when we say list comprehension, it doesn't strictly mean that you can only work with list. You can work with other sequences like strings
name = "Andy"
letters_list = [letter for letter in name]
-----
letters_list = ['A', 'n', 'd', 'y']
range_list = [n * 2 for n in range(1, 5)]
-----
range_list = [2, 4, 6, 8]
Conditional List Comprehension
- We can also tag on two more keywords; if and a test. What this is going to allow us to do is to only add this new item and only to perform this code if the test actually passes.
#Keyword Method
new_list = [new_item for item in list if test]
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Elanor', 'Freddie']
short_names = [name for name in names if len(name) < 5]
long_names = [name.upper() for name in names if len(name) >= 5]
------
short_names = ['Alex', 'Beth', 'Dave']
long_names = ['CAROLINE', 'ELANOR', 'FREDDIE']