Friday, June 19, 2020

Python Blog 4: loops, list comprehension

If else,for Loop, Range and List Comprehension


Introduction

In this blog we will look at some loop constructs and how to use list comprehension to replace loop


If else construct

Lets look at how to write an if else Construct


x = 6;
if x<5:
 x = x + 1
elif x>5:
 x = x-1
else:
 x = x * 2
 
print(x)
5

If else can be used when we want to test some conditions and based on that execute something


For loops


a = [1,2,3,4,5]
type(a)
<class 'list'>
for i in a:
    print(i)
1
2
3
4
5

All the elements in a were printed in new line. If we want to print them in a single line, use end=" " argument within print statement


Store the letters of a string in the List using For Loop

s='this is a sampe string'
l1=[]

for i in s:
    l1.append(i)
    
print(l1)
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 'a', 'm', 'p', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g']


Remove all the occurences of value using For Loop

x=[1,2,3,4,5,5,6]
val_remove=5
l1=[]

for i in x:
    if i == val_remove:
        temp=1
    else:
        l1.append(i)


print(l1)
[1, 2, 3, 4, 6]

3 elements are stored in the array with each having 3 elements of its own


While loop

While loop is used in slightly different way in comparison to for loop. Here, the counter usually decreases with each iteration

count = 10

while count >0:
    print(count, end=" ")
    count=count-1
    
    
10 9 8 7 6 5 4 3 2 1 


Reverse a string using while loop

str2 = "Data Science Class"

# Empty string
rev_str=""
length = len(str2)
length
    
18
while length >0:
    rev_str = rev_str + str2[length-1]
    length=length-1
    
print(rev_str)
ssalC ecneicS ataD


Range Function

Use to create a sequence of numbers

for i in range(5):
    print(i,end=" ")
0 1 2 3 4 

we can see that the numbers start from 0 and go to 4.Basically from 0 to n-1 where n is the argument given to range function


Create Fibonacci series using while loop


# first two terms
n1=0
n2=1
nterms=5
count=0
# First check if the number of terms i valid
if nterms <=0:
    print("Please enter a positive integer")
elif nterms==1:
    print("Fibonacci series upto the nth term is :" )
    print(n1)
else:
    print("Fibonacci series upto the nth term is :")
    while count < nterms:
        print(n1, end=",")
        nth=n1+n2
        #update values
        n1=n2
        n2=nth
        count=count+1
Fibonacci series upto the nth term is :
0,1,1,2,3,


List Comprehension: It is used when we want to do a lot different computation and maintain concise code for it. The

general format is:

[exp for val in collection if condition]

The above lines of code are equivalent to the following steps: result=[] for val in collection: if condition: result.append(exp)


Get the length of each element of string


str1=['a','as','bat','better']

y=[len(i) for i in str1]
print(y)
[1, 2, 3, 6]


Convert the Strings into lower case


lst1 = ["THIS", "IS", "A","LIST","COMPREHENSION","EXAMPLE"]
z=[ x.lower() for x in lst1]
print(z)
['this', 'is', 'a', 'list', 'comprehension', 'example']


Detect digits in a string

str1="This string contains 1245678 dfd456df numbers"
ls_dig=[x for x in str1 if x.isdigit()]
print(ls_dig)
['1', '2', '4', '5', '6', '7', '8', '4', '5', '6']


Replace Nested loop with list comprehension

for i in range(1,5):
    for j in range(1,4):
        print(i+j, end = " ")
2 3 4 3 4 5 4 5 6 5 6 7 

Using list comprehension for nested loop


ls_nested=[i+j for i in range(1,5) for j in range(1,4)]
print(ls_nested)
[2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7]


Final Comments

In this blog we saw how to use ifelse construct along with the usage of for and while loops. In the end we saw how list comprehensions can be used as a substitute for loops


No comments:

Post a Comment

Web Scraping Tutorial 4- Getting the busy information data from Popular time page from Google

Popular Times Popular Times In this blog we will try to scrape the ...