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

In [115]:
num = range(10)
num

 

Out[115]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

lets grab all the even numbers from that list

In [116]:
evens = []
for x in num:
    if(x%2 == 0):
        evens.append(x)

 

In [117]:
evens

 

Out[117]:
[0, 2, 4, 6, 8]

lets use a list comperehension

In [118]:
evens2 = []

 

In [119]:
evens2  = [x for x in num if x%2 ==0]
evens2

 

Out[119]:
[0, 2, 4, 6, 8]

lets to do a square of the even numbers

In [120]:
squaredEvens = [x**2 for x in num if x%2 == 0 and x >4]
squaredEvens

 

Out[120]:
[36, 64]

we can save it in a set form

In [121]:
squaredEvensSet = set([x**2 for x in num if x%2 == 0 and x >4])
squaredEvensSet

 

Out[121]:
{36, 64}

we can also use set in place of list in the for loop

In [122]:
squaredEvens1 = set([x**2 for x in squaredEvensSet if x%2 == 0 and x >4])
squaredEvens1

 

Out[122]:
{1296, 4096}

lets get letter , num pair for each letter in ‘abcd’ and number ‘0123’

In [123]:
my_list = []
for letter in 'abcd':
    for num in range(4):
        my_list.append((letter, num))

 

In [124]:
my_list

 

Out[124]:
[('a', 0),
 ('a', 1),
 ('a', 2),
 ('a', 3),
 ('b', 0),
 ('b', 1),
 ('b', 2),
 ('b', 3),
 ('c', 0),
 ('c', 1),
 ('c', 2),
 ('c', 3),
 ('d', 0),
 ('d', 1),
 ('d', 2),
 ('d', 3)]

we can use list comprehension to achieve the same result

In [125]:
my_list2 = [(letter, num) for letter in 'abcd' for num in range(4)] # 
my_list2

 

Out[125]:
[('a', 0),
 ('a', 1),
 ('a', 2),
 ('a', 3),
 ('b', 0),
 ('b', 1),
 ('b', 2),
 ('b', 3),
 ('c', 0),
 ('c', 1),
 ('c', 2),
 ('c', 3),
 ('d', 0),
 ('d', 1),
 ('d', 2),
 ('d', 3)]

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

In [ ]:

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

In [126]:
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)

 

Out[126]:
[('Bruce', 'Batman'),
 ('Clark', 'Superman'),
 ('Peter', 'Spiderman'),
 ('Logan', 'Wooverine'),
 ('Wade', 'Deadpool')]

Now with for loop we can get a dictionary of name being key and heroe being value

In [127]:
my_dict = {}
for name, hero in zip(names, heroe):
    my_dict[name] = hero

 

In [128]:
my_dict

 

Out[128]:
{'Bruce': 'Batman',
 'Clark': 'Superman',
 'Logan': 'Wooverine',
 'Peter': 'Spiderman',
 'Wade': 'Deadpool'}

we can do the same thing using comprehension. hence dictionary comprehension

In [129]:
my_dict2  = {name: hero for name, hero in zip(names, heroe)}

 

In [130]:
my_dict2

 

Out[130]:
{'Bruce': 'Batman',
 'Clark': 'Superman',
 'Logan': 'Wooverine',
 'Peter': 'Spiderman',
 'Wade': 'Deadpool'}

We can add if clauses as usual

In [131]:
my_dict_if = {name: hero for name, hero in zip(names, heroe) if name != 'Peter'}
my_dict_if

 

Out[131]:
{'Bruce': 'Batman',
 'Clark': 'Superman',
 'Logan': 'Wooverine',
 'Wade': 'Deadpool'}
In [ ]:

A SET has UNIQUE VALUES

lets have list which has duplicates and add to a set and see how it behaves

In [132]:
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)

 

In [133]:
myset

 

Out[133]:
{'1', '2', '3', '4', '5', '8', '9'}

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

In [134]:
myset2 = {n for n in nums3}#

myset2

 

Out[134]:
{'1', '2', '3', '4', '5', '8', '9'}
In [ ]:

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

In [135]:
nums_gen = [1,5,2,5,2,6,2,86,5,2,8,2]

 

In [136]:
def gen_func(num):
    for n in nums:
        yield n*n

 

In [137]:
my_gen = gen_func(nums_gen)
#my_gen

 

lets get the values from my_gen

In [143]:
for i in my_gen:
    print(i)

 

We can do the same thing with GENERATOR

In [140]:
my_gen2 = (n*n for n in nums_gen)

 

now lets iterate through my_gen2

In [141]:
for y in my_gen2:
    print(y)

 

1
25
4
25
4
36
4
7396
25
4
64
4

 

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *