Thursday, 11 June 2020

List Comprehensions in Python

Getting started with List comprehensions in Python

List Comprehensions provide a concise and elegant way to create new lists based on the

existing lists or other iterable. List Comprehensions has a variable that iterates over existing list using

for-loop and conditional statements.

Note: conditional statements may or may not be present in the List Comprehensions.

 

Syntax to construct List Comprehensions in Python:

new_list = [variable  for variable in old_list if condition]


Without Conditional Statement:

Suppose, you want to create a list with each element is square of each element of existing list

exist_list = [1, 2, 3, 4, 5, 6, 7, 8]

squared_list = [var**2 for var in exist_list]

print(squared_list)

Output: [1, 4, 9, 16, 25, 36, 49, 64]

 

Using Conditional Statement in List comprehensions:

Now, you want to create a list with each element is multiple of 5 from an existing list

exist_list = [1, 5, 6, 10, 14, 15, 25, 30] 

is_multiple_of_five = [var for var in exist_list if var % 5 == 0 ]

print(is_multiple_of_five)

Output: [5, 10, 15, 25, 30]

 

 

 

 

How to create a Virtual Environment in Python

Why do you need to create a Virtual Environment?

Sometimes, we need to have some dependencies of your project to be isolated
from dependencies present in the system site to avoid conflicts and Virtual 
Environment lets you do this.

Creating a virtual environment lets you have your own independent set of 
installed Python packages in your site directories which is apart from system
site directories. Virtual Environment lets you create an isolated environment 
for your python projects.


Creating a Virtual Environment :

Step 1: Install Virtual Environment package:

pip install virtualenv


Step 2: Create a new directory to work with and head over there:

mkdir venv
cd venv


Step 3: Now, create a new Virtual Environment in this directory

virtualenv myvenv

This creates a new virtual environment with the name "myvenv".


For using this Environment's packages you need to activate it.

Step 4: Activate the environment 

myvenv\Scripts\activate

Now you are in virtual environment and ready to go with it.


Step 5: Deactivate the virtual environment

deactivate