Python List Comprehension Dictionary Set Comprehension and For Loops
This is a guide on Python List comprehension. List comprehension is a great way to write simple and easy to read Python codes. You can use it dictionaries and sets as well.
Credits to Corey Schafer , creator of Python course materials.
lets create a list
1 2 |
num = range(10) num |
lets grab all the even numbers from that list
1 2 3 4 |
evens = [] for x in num: if(x%2 == 0): evens.append(x) |
1 |
evens |
lets use a list comperehension
1 |
evens2 = [] |
1 2 |
evens2 = [x for x in num if x%2 ==0] evens2 |
lets to do a square of the even numbers
1 2 |
squaredEvens = [x**2 for x in num if x%2 == 0 and x >4] squaredEvens |
we can save it in a set form
1 2 |
squaredEvensSet = set([x**2 for x in num if x%2 == 0 and x >4]) squaredEvensSet |
we can also use set in place of list in the for loop
1 2 |
squaredEvens1 = set([x**2 for x in squaredEvensSet if x%2 == 0 and x >4]) squaredEvens1 |
lets get letter , num pair for each letter in ‘abcd’ and number ‘0123’
1 2 3 4 |
my_list = [] for letter in 'abcd': for num in range(4): my_list.append((letter, num)) |
1 |
my_list |
we can use list comprehension to achieve the same result
1 2 |
my_list2 = [(letter, num) for letter in 'abcd' for num in range(4)] # my_list2 |
tne parameters in the tuple should be match the parameters in the for loop . that is letter, should match letter in for loop and num
should match num in for loop. you cannot have letter in tuple or let in for number. neither can you havve num in tuple and number in
for loop
We can also use list comprehension with dictionaries.
Lets create 2 lists and make a tuple of out it and then get a dictionary from the tuple
1 2 3 4 5 |
names= ['Bruce','Clark','Peter','Logan','Wade'] heroe = ['Batman','Superman','Spiderman','Wooverine','Deadpool'] #lets use a zip to turn these 2 lists into a tuple zip(names, heroe) |
Now with for loop we can get a dictionary of name being key and heroe being value
1 2 3 |
my_dict = {} for name, hero in zip(names, heroe): my_dict[name] = hero |
1 |
my_dict |
we can do the same thing using comprehension. hence dictionary comprehension
1 |
my_dict2 = {name: hero for name, hero in zip(names, heroe)} |
1 |
my_dict2 |
We can add if clauses as usual
1 2 |
my_dict_if = {name: hero for name, hero in zip(names, heroe) if name != 'Peter'} my_dict_if |
A SET has UNIQUE VALUES
lets have list which has duplicates and add to a set and see how it behaves
1 2 3 4 5 6 |
nums3 = ['1','1','2','2','3','4','5','4','3','8','8','9','2'] #lets loop it through a for loop and add to a set. myset = set() for n in nums3: myset.add(n) |
1 |
myset |
it returns only uniques values as SETS only contain unique values
We can accomplish the same thing with SET comprehension which also takes a curly bracket
1 2 3 |
myset2 = {n for n in nums3}# myset2 |
GENERATORS. they are very similar to list comprehension but they USE PARENTHESIS ie ()
and the results can be iterated through
Lets look at one quick example
We want to get n*n for each n in nums
1 |
nums_gen = [1,5,2,5,2,6,2,86,5,2,8,2] |
1 2 3 |
def gen_func(num): for n in nums: yield n*n |
1 2 |
my_gen = gen_func(nums_gen) #my_gen |
lets get the values from my_gen
1 2 |
for i in my_gen: print(i) |
We can do the same thing with GENERATOR
1 |
my_gen2 = (n*n for n in nums_gen) |
now lets iterate through my_gen2
1 2 |
for y in my_gen2: print(y) |