creates a new list with the results from evaluation the expression on the for and if clauses
[ expression for item in list if conditional ]
Old Way
new_list = [] for i in old_list: if filter(i): new_list.append(expressions(i))
List Comprehension way
new_list = [expression(i) for i in old_list if filter(i)]
if filter(i) - apply a filter with an if
new_range = [i * i for i in range(5) if i % 2 == 0]
*result* = [*transform* *iteration* *filter* ] - The * operator is used to repeat. The filter part answers the question if the
item should be transformed.
Create a list
x = [i for i in range(10)]
print x
# This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
List using loops and list comprehension You can either use loops: squares = []
for x in range(10):
squares.append(x**2)
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Or you can use list comprehensions to get the same result: squares = [x**2 for x in range(10)]
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
multiply parts of list list1 = [3,4,5]
multiplied = [item*3 for item in list1]
print multiplied
[9,12,15]
first letter of each word
listOfWords = ["this","is","a","list","of","words"]
items = [ word[0] for word in listOfWords ]
print items
lower/upper case
>>> [x.lower() for x in ["A","B","C"]]
['a', 'b', 'c']
>>> [x.upper() for x in ["a","b","c"]]
['A', 'B', 'C']
print out the numbers from a given string
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
print numbers
>> ['1', '2', '3', '4', '5']
Parse a file using list comprehension
fh = open("test.txt", "r")
result = [i for i in fh if "line3" in i]
print result
List Comprehension in functions
Create a function and name it double: def double(x): return x*2
If you now just print that function with a value in it, it should look like this: »> print double(10) 20
>>> [double(x) for x in range(10)]
print double
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
You can put in conditions:
>>> [double(x) for x in range(10) if x%2==0]
[0, 4, 8, 12, 16]
You can add more arguments:
>>> [x+y for x in [10,30,50] for y in [20,40,60]]
[30, 50, 70, 50, 70, 90, 70, 90, 110]
[Home](/reading-notes/)