|

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

In [115]:

 

Out[115]:

lets grab all the even numbers from that list

In [116]:

 

In [117]:

 

Out[117]:

lets use a list comperehension

In [118]:

 

In [119]:

 

Out[119]:

lets to do a square of the even numbers

In [120]:

 

Out[120]:

we can save it in a set form

In [121]:

 

Out[121]:

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

In [122]:

 

Out[122]:

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

In [123]:

 

In [124]:

 

Out[124]:

we can use list comprehension to achieve the same result

In [125]:

 

Out[125]:

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]:

 

Out[126]:

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

In [127]:

 

In [128]:

 

Out[128]:

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

In [129]:

 

In [130]:

 

Out[130]:

We can add if clauses as usual

In [131]:

 

Out[131]:
In [ ]:

A SET has UNIQUE VALUES

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

In [132]:

 

In [133]:

 

Out[133]:

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]:

 

Out[134]:
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]:

 

In [136]:

 

In [137]:

 

lets get the values from my_gen

In [143]:

 

We can do the same thing with GENERATOR

In [140]:

 

now lets iterate through my_gen2

In [141]:

 

 

Want more information like this?

Similar Posts

Leave a Reply

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