Untitled Document
Comprehensions - List, Sets and Dictionaries
```       #********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****
# Here we will see different examples of comprehensions

# Simple Examples of LIST Comprehesions
# EX - 1 We will create another list from a given list

nums =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = [n for n in nums]
print (my_list)

# EX - 2 Creating  list of square of numbers from a given list

nums =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = [n*n for n in nums]
print (my_list)

# EX - 3 Creating  list of Even Numbers from given list

nums =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list = [n for n in nums if n % 2 == 0]
print (my_list)

# EX - 4  Nested Loop Example in list comprehensions
# IMP - As we are passing two variables in comprehensions - we need to combine those varibale in tuple -(letter,num)
# If we don't combine them in tuple or in list and keep independent then we will get error

nums =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list=[(letter,num) for letter in 'abcd' for num in range(1,5)]
print(my_list)

```
```       #********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****
# Combining two lists using zip function

# Below example will print elements from 0th index to 4th index
num =[1, 2, 3, 4, 5]
letter=['a', 'b', 'c', 'd', 'e']
print(zip(num,letter))
```
```       #********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****
# Creating a dictionary using comprehensions
# EX - 1

num =[1, 2, 3, 4, 5]
letter=['a', 'b', 'c', 'd', 'e']
my_dict = {n : l for n, l in zip(num, letter)}
print(my_dict)

# EX - 2 Creating a dictionary using comprehensions with if statement

num =[1, 2, 3, 4, 5]
letter=['a', 'b', 'c', 'd', 'e']
my_dict = {n : l for n, l in zip(num, letter) if n != 3 }
print(my_dict)
```
Untitled Document