1. List Comprehension
List comprehension is to creat a new list quickly. Example:
# list comprehension
>>> mylist = [1,2,2,3,4,4]
>>> newlist1 = [x**2 for x in mylist] #square
>>> newlist1
[1, 4, 4, 9, 16, 16]
>>> newlist2 = [x+1 for x in mylist if x%2==0]
>>> newlist2
[3, 3, 5, 5]
2. Set comprehension
The difference of list and set is that elements in set are unique while list not. Example:
# set comprehension
>>> newset = {x+1 for x in mylist}
>>> newset
set([2, 3, 4, 5])
an alternative solution is
>>> newlist3 = [x+1 for x in mylist]
>>> newlist3
[2, 3, 3, 4, 5, 5]
>>> newset1 = set(newlist3)
>>> newset1
set([2, 3, 4, 5])
3. Dictionary Comprehension
Example:
# dictionary comprehension
>>> newdict = {x:x-1 for x in mylist}
>>> newdict
{1: 0, 2: 1, 3: 2, 4: 3}