0% found this document useful (0 votes)
30 views29 pages

PRAC-1 - Jupyter Notebook

The document demonstrates various numeric, string, and data structure operations in Python like addition, subtraction, slicing, indexing, sorting, copying using examples in Jupyter Notebook. It covers the basic concepts of numbers, variables, strings, tuples, lists and their commonly used methods.

Uploaded by

iamtushar1140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views29 pages

PRAC-1 - Jupyter Notebook

The document demonstrates various numeric, string, and data structure operations in Python like addition, subtraction, slicing, indexing, sorting, copying using examples in Jupyter Notebook. It covers the basic concepts of numbers, variables, strings, tuples, lists and their commonly used methods.

Uploaded by

iamtushar1140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

SESSION-1

NUMBERS:

In [1]: # Addition

6 + 2

Out[1]: 8

In [2]: # Subtraction

6 - 2

Out[2]: 4

In [3]: # Multiplication

6 * 2

Out[3]: 12

In [4]: # Division

6 / 2

Out[4]: 3.0

In [5]: # Floor Division



9 // 2
# Answer shoud be 4.5 but considering only the floor value the answer is 4.

Out[5]: 4

In [6]: # Exponential / Power



6 ** 2

Out[6]: 36

In [7]: # BODMAS

int((9 + 4) - 5 * 3 + (8 / 2) + (9 - 2))

Out[7]: 9

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 1/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [8]: # Math Library



import math as m
int(m.sqrt(625))

Out[8]: 25

VARIABLES:

In [9]: x = 7
y = 8.5
x + y

Out[9]: 15.5

In [10]: # Dtype of x

x,type(x),y,type(y)

Out[10]: (7, int, 8.5, float)

In [11]: # Dtype of x + y

type(x + y)

Out[11]: float

STRINGS:
Strings are Immutable.

In [12]: z = 'Tushar Shekhar'


z

Out[12]: 'Tushar Shekhar'

In [13]: # Dtype of z

type(z)

Out[13]: str

In [14]: # Length of z

len(z)

Out[14]: 14

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 2/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [15]: # Forward - Indexing



z[5]

Out[15]: 'r'

In [16]: # Reverse - Indexing



z[-4]

Out[16]: 'k'

In [17]: # Slicing x to end



z[5:]

Out[17]: 'r Shekhar'

In [18]: # Slicing start to x



z[:4]

Out[18]: 'Tush'

In [19]: # Slicing x to y

z[5:11] # 5 included but 11 not included.

Out[19]: 'r Shek'

In [20]: # Slicing with step count [1 to 9 - 10 not included and 2 is the step count

z[1:10:2]

Out[20]: 'uhrSe'

In [21]: # Capitalize

# Capitalizes the first letter of first word in the string.
program = 'data science'
program.capitalize()

Out[21]: 'Data science'

In [22]: # Title

# Capitalizes the first letter of all the words in the string.
program.title()

Out[22]: 'Data Science'

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 3/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [23]: # Index of particular char.



# If char comes 2 or more times then it returns the first index of occurenc
program.index('a')

Out[23]: 1

In [24]: # Index of particular char.



program.index('c')

Out[24]: 6

In [25]: # Upper Function: It UpperCases all the letters in the string for all the w
# Lower Function: It LowerCases all the letters in the string for all the w

program.upper()

Out[25]: 'DATA SCIENCE'

In [26]: # Split function: It seperates the words and store them as an item in the l

program.split()

Out[26]: ['data', 'science']

In [27]: # Split function: It seperates the words from the given * char * and store
course = "Python-for-Chitkara"
course.split('-')

Out[27]: ['Python', 'for', 'Chitkara']

In [28]: # Dtype of input: STR always.



type(input('Enter Number: '))

Enter Number: 15

Out[28]: str

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 4/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [29]: # Strings are Immutable.



subject = 'Python'
subject[0] ='B'
subject

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[29], line 4
1 # Strings are Immutable.
3 subject = 'Python'
----> 4 subject[0] ='B'
5 subject

TypeError: 'str' object does not support item assignment

DATA STRUCTURES:

TUPLES:

Tuples are Immutable.

In [30]: t1 = (2,4,'Data',6,8,10,'Python')
t1

Out[30]: (2, 4, 'Data', 6, 8, 10, 'Python')

In [31]: # Access particular index.



t1[4]

Out[31]: 8

In [32]: # Tuple Slicing



t1[2:5]

Out[32]: ('Data', 6, 8)

In [33]: # Count the freq of any char.



t2 = (2,4,8,8,6,5,3,2,4,7,8,9,5,4,1,2,8,6)
t2.count(8)

Out[33]: 4

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 5/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [34]: # Index of particular data item.



t2.index(1)

Out[34]: 14

In [35]: # Length of tuple.



len(t1)

Out[35]: 7

In [36]: # Max value of tuple.



#This works when Dtypes is same for all data members.

max(t2)

Out[36]: 9

In [37]: # Min value of tuple.



#This works when Dtypes is same for all data members.

min(t2)

Out[37]: 1

In [38]: # Tuples are Immutable.



t1[2] = 8

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[38], line 3
1 # Tuples are Immutable.
----> 3 t1[2] = 8

TypeError: 'tuple' object does not support item assignment

LISTS:

In [39]: l1 = [2,4,6,8,10]
l1

Out[39]: [2, 4, 6, 8, 10]

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 6/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [40]: # Access particular index.



l1[2]

Out[40]: 6

In [41]: # Append: Adding to the end.



l1.append(10)
l1

Out[41]: [2, 4, 6, 8, 10, 10]

In [42]: # Extend:
l2 = [9,7,5,3,1]
l2.extend(l1)
l2

Out[42]: [9, 7, 5, 3, 1, 2, 4, 6, 8, 10, 10]

In [43]: # Insert element at an particular index.



l1.insert(2,15)
l1

Out[43]: [2, 4, 15, 6, 8, 10, 10]

In [44]: # Pop out the last element.



l1.pop()
l1

Out[44]: [2, 4, 15, 6, 8, 10]

In [45]: # Remove element by itself



l1.remove(15)
l1

Out[45]: [2, 4, 6, 8, 10]

In [46]: # Sort in ASC order.



l1.sort()
l1

Out[46]: [2, 4, 6, 8, 10]

In [47]: # Sort in DESC order.



l1.sort(reverse = True)
l1

Out[47]: [10, 8, 6, 4, 2]

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 7/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [48]: # Deep Copy



l3 = l1
l3

Out[48]: [10, 8, 6, 4, 2]

In [49]: # Changing value in copied list.



l3[0] = 12
l3

Out[49]: [12, 8, 6, 4, 2]

In [50]: # The Value changes in the original list as well.



l1

Out[50]: [12, 8, 6, 4, 2]

In [51]: # Shallow Copy.



sc = l1.copy()
sc

Out[51]: [12, 8, 6, 4, 2]

In [52]: # Changing value in copied list.



sc[0] = 20
sc

Out[52]: [20, 8, 6, 4, 2]

In [53]: # The Value does not change in the original list as seen in Deep Copy.

l1

Out[53]: [12, 8, 6, 4, 2]

In [54]: # Empty the list.



sc.clear()
sc

Out[54]: []

DICTIONARY:

In [55]: d1 = {'Id': 5049,'Name': 'Tushar','Ratings': 4.2}


d1

Out[55]: {'Id': 5049, 'Name': 'Tushar', 'Ratings': 4.2}

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 8/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [56]: # Checking Dtype.



type(d1)

Out[56]: dict

In [57]: # Accessing Particular key.



d1['Name']

Out[57]: 'Tushar'

In [58]: # Changing value of particular key.



d1['Ratings'] = 4.7
d1

Out[58]: {'Id': 5049, 'Name': 'Tushar', 'Ratings': 4.7}

In [59]: # Adding new key value pair in existing dict.



d1['City'] = 'Chandigarh'
d1

Out[59]: {'Id': 5049, 'Name': 'Tushar', 'Ratings': 4.7, 'City': 'Chandigarh'}

In [60]: # List all keys in the dict.



d1.keys()

Out[60]: dict_keys(['Id', 'Name', 'Ratings', 'City'])

In [61]: # List all Values/Items in the dict.



d1.items()

Out[61]: dict_items([('Id', 5049), ('Name', 'Tushar'), ('Ratings', 4.7), ('City',


'Chandigarh')])

In [62]: d2 = {'Name':'Tushar Shekhar', 'City': 'Zirakpur','Salary':95000}


d2

Out[62]: {'Name': 'Tushar Shekhar', 'City': 'Zirakpur', 'Salary': 95000}

In [63]: d1.update(d2)
d1

Out[63]: {'Id': 5049,


'Name': 'Tushar Shekhar',
'Ratings': 4.7,
'City': 'Zirakpur',
'Salary': 95000}

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 9/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

SETS:

In [64]: # Gives a particular value only once in ASC order.



s1 = {2,4,6,8,10,10,8,8,8,6,4,4,6,8,10,2}
s1

Out[64]: {2, 4, 6, 8, 10}

In [65]: # Checking Dtype.



type(s1)

Out[65]: set

In [66]: # Converting list into sets.



list1 = [9,7,6,4,3,1,2,5,8]
s2 = set(list1)
s2

Out[66]: {1, 2, 3, 4, 5, 6, 7, 8, 9}

In [67]: # Checking Dtype



type(s2)

Out[67]: set

CONTROL STATEMENTS:
In [68]: # If-Else [Age-Voting Question]

age = int(input("Enter your Age: "))
if age >= 18:
print('You have the Right to Vote.')
else:
print("Sorry you can't vote.")

Enter your Age: 22


You have the Right to Vote.

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 10/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [69]: # If-Elif-Else [Age-Voting Question]



age = int(input("Enter your Age: "))
gender = input("Enter your gender [M/F]: ")
if age >= 18 and gender == 'M':
print('Sir, you have the Right to Vote.')
elif age >= 18 and gender == 'F':
print('Mam, you have the Right to Vote.')
else:
print("Sorry you can't vote.")

Enter your Age: 22


Enter your gender [M/F]: M
Sir, you have the Right to Vote.

In [70]: # Nested if

num1 = int(input('Enter frist number: '))
num2 = int(input('Enter second number: '))
num3 = int(input('Enter third number: '))
if num1 > num2:
if num1 > num3:
print(num1,' is greater than ', num2, ' and ',num3)
if num2 > num1:
if num2 > num3:
print(num2,' is greater than ', num1, ' and ',num3)
if num3 > num1:
if num3 > num2:
print(num3,' is greater than ', num1, ' and ',num2)

Enter frist number: 51


Enter second number: 52
Enter third number: 99
99 is greater than 51 and 52

In [71]: # Range [2-16 only interleave]



x = set(range(2,16,2)) # 16 is not included. it works for 2 to 15 only.
x

Out[71]: {2, 4, 6, 8, 10, 12, 14}

In [72]: # For Loop



x = [2, 4, 6, 8, 10, 12, 14]
x_square = [] # empty list
for i in x:
x_square.append(i**2)

x_square

Out[72]: [4, 16, 36, 64, 100, 144, 196]

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 11/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [73]: #Nested For-loop [Pattern]



for row in range(1,5):
for col in range(row):
print('*',end ="")
print()

*
**
***
****

In [74]: #Nested For-loop [Pattern]



for row in range(1,5):
for col in range(row):
print(row,end ="")
print()

1
22
333
4444

In [75]: #Nested For-loop [Pattern]



for row in range(1,5):
for col in range(row):
print(col+1,end ="")
print()

1
12
123
1234

In [76]: # While Loop



num = 1
while num <= 5:
print(num)
num += 1

1
2
3
4
5

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 12/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [77]: # Break

l1 = ['Shekhar',2,4,'Data',6,8,10,'Python',56,48,20,54,'Tushar']
for itr in l1:
if itr == 'Python':
break;
print(itr)

Shekhar
2
4
Data
6
8
10

In [78]: # Continue

l1 = ['Shekhar',2,4,'Data',6,8,10,'Python',56,48,20,54,'Tushar']
for itr in l1:
if itr == 'Data':
continue;
print(itr)

Shekhar
2
4
6
8
10
Python
56
48
20
54
Tushar

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 13/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [79]: # Question: [Letter-Digit-Symbol: frequency]



str1 = 'tushar@shekhar#5049!6280772554%7G*data)science('

alpha = 0
digits = 0
symbol = 0

for c in str1:
if c.isalpha():
alpha += 1
elif c.isdigit():
digits += 1
else:
symbol += 1
print('Alphabets = ',alpha)
print('Digits = ',digits)
print('Symbols = ',symbol)

Alphabets = 25
Digits = 15
Symbols = 7

In [80]: # Sperate positive



pos = []
l2 = [8,-5,4,6,-2,-10,-51,-12,-48,36,-74,55,-44,20]
for i in l2:
if i > 0:
pos.append(i)
pos

Out[80]: [8, 4, 6, 36, 55, 20]

In [81]: # Sperate negitive



neg = []
l2 = [8,-5,4,6,-2,-10,-51,-12,-48,36,-74,55,-44,20]
for i in l2:
if i < 0:
neg.append(i)
neg

Out[81]: [-5, -2, -10, -51, -12, -48, -74, -44]

FUNCTIONS:

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 14/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [82]: # Defining and Calling the function:




def sim_greet(): # Define the function
print('Hello Buddy, Keep Studying :)')

sim_greet() # Calling the function

Hello Buddy, Keep Studying :)

In [83]: # Passing info to function



def name_greet(name):
print("Hello",name,',', 'Welcome to Python Prac-1. Enjoy Learning :)')

name_greet('Tushar Shekhar')

Hello Tushar Shekhar , Welcome to Python Prac-1. Enjoy Learning :)

In [84]: def multiply(n1,n2):


print(n1 * n2)

multiply(20,3)

60

In [85]: # Print V/S Return

# Print is of nonetype and can't be enhanced gives error where as return ca



def multiply(n1,n2):
print(n1 * n2)

multiply(20,3) + 10

# To solve this we can use return instead of print.

60

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[85], line 8
5 def multiply(n1,n2):
6 print(n1 * n2)
----> 8 multiply(20,3) + 10

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 15/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [86]: # Solving above using return.



def multiply(n1,n2):
return(n1 * n2)

multiply(20,3) + 10

Out[86]: 70

In [87]: # Positional Arguements



def student(name,age):
print('Name: ',name)
print('Age: ',age)

student(22,'Tushar Shekhar')

# Here the values are incorrect as we called the function with positional a

Name: 22
Age: Tushar Shekhar

In [88]: # Keyword Arguements



def student(name,age):
print('Name: ',name)
print('Age: ',age)

student(age = 22,name = 'Tushar Shekhar')



# Here the result for same above function is Correct as we have called the f

Name: Tushar Shekhar


Age: 22

In [89]: # Variable length arguements. [*]



def sum_num(*num):
sum = 0
for i in num:
sum += i
return sum

sum_num(9,7,6,4,3,1,2,8,10)

Out[89]: 50

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 16/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [90]: # Variable Keyword length arguements. [**]



def info(**reg):
for i,j in reg.items():
print(i,j)

info(name = 'Tushar Shekhar', age = 22, course = 'Data Science', Ratings =

name Tushar Shekhar


age 22
course Data Science
Ratings 4.7

In [91]: # Prime or not using For-Else



def prime(num):
for i in range(2,int(num/2)):
if num % i == 0:
print(num,' is not a prime number.')
break;
else:
print(num,' is a prime number.')

prime(37)

37 is a prime number.

In [92]: # Reverse the digits of the number.



def rev_num(n):
strn = str(n)
nstr = strn[::-1]
nn = int(nstr)
return nn

rev_num(24689)

Out[92]: 98642

In [93]: # Scope of variable



num = 10

def scope():
num = 15
print('Inside function = ',num)

scope()
print('Outside function = ',num)

Inside function = 15
Outside function = 10

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 17/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [94]: # Return palindrome str



def palindrome_str(*strings):
res = []
for word in strings:
if word == word[::-1]:
res.append(word)
return res

palindrome_str('racecar','vishvas','radar','sankalp','string','madam','mom'

Out[94]: ['racecar', 'radar', 'madam', 'mom', 'nitin']

In [95]: # RECURSION - Factorial



def factorial(number):
if(number == 0 or number == 1):
return 1
else:
return number * factorial(number - 1)

factorial(5)

Out[95]: 120

In [96]: # RECURSION - Fibonacci



def fibo(number):
if number <= 1:
return number
return(fibo(number - 1) + fibo(number - 2))

# print series:
num = int(input('Enter number: '))
for i in range(num):
print(fibo(i))

Enter number: 8
0
1
1
2
3
5
8
13

In [97]: # ANONYOMOUS / INLINE FUNCTIONS:



# Addition

add = lambda a,b: a + b
add(5,6)

Out[97]: 11

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 18/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [98]: # Subtraction

sub = lambda a,b: a - b
sub(15,6)

Out[98]: 9

In [99]: # Division

div = lambda a,b: a / b
div(54,6)

Out[99]: 9.0

In [100]: # Multiplication

mul = lambda a,b: a * b
mul(5,6)

Out[100]: 30

In [101]: # Square

sqr = lambda a: a ** 2
sqr(5)

Out[101]: 25

In [102]: # Cube

cube = lambda a: a ** 3
cube(5)

Out[102]: 125

In [103]: # Number div by 19 and 13



list1 = [19, 65, 57, 39, 152, 639, 121, 44, 90, 190]
res = list(filter(lambda x: (x%19==0) or (x%13==0),list1))
res

Out[103]: [19, 65, 57, 39, 152, 190]

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 19/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [104]: # words with less than 5 letters



string = 'It is a long established fact that a reader will be distracted by
split_words = string.split()
res = list(filter(lambda y: len(y)<5,split_words))
res

Out[104]: ['It',
'is',
'a',
'long',
'fact',
'that',
'a',
'will',
'be',
'by',
'the',
'of',
'a',
'page',
'when',
'at',
'its']

In [105]: # sum all elements in a list



from functools import reduce

lis = [5,6,2,4,8,9,6,3,2,1]
res = reduce(lambda x,y: x + y,lis)
res

Out[105]: 46

In [106]: # Square of all elements in the list



list2 = [5,6,2,4,8,9,6,3,2,1]
res = list(map(lambda x: x**2,list2))
res

Out[106]: [25, 36, 4, 16, 64, 81, 36, 9, 4, 1]

In [107]: # Cube of all the elements in the list


list3 = [5,6,2,4,8,9,6,3,2,1]
res = list(map(lambda x: x**3,list3))
res

Out[107]: [125, 216, 8, 64, 512, 729, 216, 27, 8, 1]

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 20/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

List Comprehension
In [108]: # Square of numbers in the list using list comprehension method.

list1 = [n*n for n in [6, 3, 2, 5, 4, 7]]
list1

Out[108]: [36, 9, 4, 25, 16, 49]

In [109]: # Uppercasing all the letters in the string using list comprehension method

list2 = [s.upper() for s in 'TusharShekhar']
list2

Out[109]: ['T', 'U', 'S', 'H', 'A', 'R', 'S', 'H', 'E', 'K', 'H', 'A', 'R']

In [110]: # Print only vowels and * for constants in the string using list comprehens

str_name = 'TusharShekhar'
res = [i if i in 'aeiou' else '*' for i in str_name]
res

Out[110]: ['*', 'u', '*', '*', 'a', '*', '*', '*', 'e', '*', '*', 'a', '*']

In [111]: # Print only +ve and * for -ve in the tuple using list comprehension method

tuple1 = (2, 4, -1, 8, 9, -5, 10, 12, -12)
result = [i if i > 0 else '*' for i in tuple1]
result

Out[111]: [2, 4, '*', 8, 9, '*', 10, 12, '*']

In [112]: # Print only +ve and the ones divisible by 2 and * for rest in the tuple us

tuple1 = (2, 4, -1, 8, 9, -5, 10, 12, -12)
result = [i if i > 0 else '*' for i in tuple1 if i % 2 ==0]
result

Out[112]: [2, 4, 8, 10, 12, '*']

Dictionary Comprehension
In [113]: # Print number with their square using dictionary comprehension method.

dict1 = {d:d*d for d in range(1,11)}
dict1

Out[113]: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 21/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [114]: # Print number with their string with their length using dictionary compreh

strings = ['Tushar','Shekhar','Introduction','To','Python']
dict2 = {i:len(i) for i in strings}
dict2

Out[114]: {'Tushar': 6, 'Shekhar': 7, 'Introduction': 12, 'To': 2, 'Python': 6}

Insert, Append, Pop in list

In [115]: # Write a program to remove the item present at index 4 and add it to the 2

list1 = [54, 44, 27, 79, 91, 41]
remindx = list1.pop(4)
list1.insert(1,remindx)
list1.append(remindx)
list1

Out[115]: [54, 91, 44, 27, 79, 41, 91]

In [116]: # Seprate +ve and -ve tweets question [List Comprehension]



positive = ['good','awesome', 'best', 'nice']

negative = ['worst','awful', 'bad']

tweets = [ 'This government policies are good', 'bad implementation', 'The

pos_twt = [x for x in tweets for i in x.split() if i in positive]
neg_twt = [x for x in tweets for i in x.split() if i in negative]
print('Positive Tweets: ')
print(pos_twt)
print('Negative Tweets: ')
print(neg_twt)

Positive Tweets:
['This government policies are good', 'The way he played showed that he is
one of the best players in the world', 'Her acting in the play was awesom
e', "It's nice to hear this little kid's laugh"]
Negative Tweets:
['bad implementation', 'The wine tastes awful']

In [117]: # Sour Fruits question [Dictionary Comprehension]



fruits = (('Lemon','sour'), ('DragonFruit', 'Sweet'), ('Grapes','sour'), ('
res = [x[0] for x in fruits if x[1].lower() == 'sour']
res

Out[117]: ['Lemon', 'Grapes', 'Kiwi', 'Orange', 'Limes']

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 22/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [118]: # Seperate integers from string question [List Comprehension]



l1 = ['a',1,2,'b',4,5,0,'C',3,6,"python",7,8]
result = [i for i in l1 if type(i)==int]
result

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

In [119]: # Reverse the string with opposite case [Swapcase() Function]



string = 'HeLlO wOrLd'
res = string.swapcase()[::-1]
res

Out[119]: 'DlRoW oLlEh'

Numpy
In [120]: import numpy as np

import warnings
warnings.filterwarnings('ignore')

In [122]: array1 = np.array([4,5,6,1,3,2])


array1

Out[122]: array([4, 5, 6, 1, 3, 2])

In [123]: type(array1)

Out[123]: numpy.ndarray

In [124]: array1.shape

Out[124]: (6,)

In [125]: array1.ndim

Out[125]: 1

In [126]: # Multi D array



array2 = np.array([[1,4,7],[2,5,8],[3,6,9]])
array2

Out[126]: array([[1, 4, 7],


[2, 5, 8],
[3, 6, 9]])

In [127]: array2.shape

Out[127]: (3, 3)

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 23/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [128]: array2.ndim

Out[128]: 2

Arange and Linspace

In [129]: np.arange(2,22,2)

Out[129]: array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

In [130]: np.arange(2,22,2.8)

Out[130]: array([ 2. , 4.8, 7.6, 10.4, 13.2, 16. , 18.8, 21.6])

In [131]: # Linspace

np.linspace(2,22,12)

Out[131]: array([ 2. , 3.81818182, 5.63636364, 7.45454545, 9.27272727,


11.09090909, 12.90909091, 14.72727273, 16.54545455, 18.36363636,
20.18181818, 22. ])

In [133]: # Zeros array



np.zeros((3,3))

Out[133]: array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

In [135]: # Identical array



np.eye(3)

Out[135]: array([[1., 0., 0.],


[0., 1., 0.],
[0., 0., 1.]])

In [136]: # Diagonal array



np.diag([2,4,6])

Out[136]: array([[2, 0, 0],


[0, 4, 0],
[0, 0, 6]])

Random Number Generation

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 24/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [140]: # Generates random like [0.__] but only +ve numbers only.

np.random.rand(3,3)

Out[140]: array([[0.68903377, 0.61882101, 0.99766541],


[0.00921782, 0.72365046, 0.16113463],
[0.02218618, 0.55078951, 0.16277934]])

In [141]: # Generates random like [0.__] including Negatives also



np.random.randn(3,3)

Out[141]: array([[-0.35796348, 0.28637373, -0.4188792 ],


[-0.58962507, -0.7269684 , 0.94427174],
[-0.03465964, 0.25899539, -0.31799249]])

In [142]: # Generates random integers.



np.random.randint(11,22,(3,3))

Out[142]: array([[18, 15, 20],


[14, 14, 14],
[13, 15, 19]])

Masking in Numpy

In [144]: matrix = np.random.randint(11,22,(3,4))


matrix

Out[144]: array([[20, 19, 13, 21],


[15, 17, 13, 11],
[17, 21, 19, 21]])

In [146]: # Bool Masking



matrix>15

Out[146]: array([[ True, True, False, True],


[False, True, False, False],
[ True, True, True, True]])

In [148]: # Condtional Masking



matrix[matrix>15]

Out[148]: array([20, 19, 21, 17, 17, 21, 19, 21])

In [153]: matrix.shape

Out[153]: (3, 4)

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 25/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [151]: matrix.reshape(4,3)

Out[151]: array([[20, 19, 13],


[21, 15, 17],
[13, 11, 17],
[21, 19, 21]])

Broadcasting

In [155]: z1 = np.zeros((3,3))
z1

Out[155]: array([[0., 0., 0.],


[0., 0., 0.],
[0., 0., 0.]])

In [156]: z2 = z1 + 10
z2

Out[156]: array([[10., 10., 10.],


[10., 10., 10.],
[10., 10., 10.]])

In [157]: # Row Broadcasting



a_r = [5,15,25]
rb = z2 + a_r
rb

Out[157]: array([[15., 25., 35.],


[15., 25., 35.],
[15., 25., 35.]])

In [162]: a_c = np.array([[2,4,6]])


a_c = a_c.T
cb = z2 + a_c
cb

Out[162]: array([[12., 12., 12.],


[14., 14., 14.],
[16., 16., 16.]])

In [163]: # Identical matrix with any constant number



np.full((3,3),5)

Out[163]: array([[5, 5, 5],


[5, 5, 5],
[5, 5, 5]])

Argmin and Argmax

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 26/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [164]: nm = np.random.randint(22,55,(3,3))
nm

Out[164]: array([[44, 52, 35],


[23, 36, 29],
[34, 37, 22]])

In [165]: np.argmin(nm)

Out[165]: 8

In [166]: np.argmax(nm)

Out[166]: 1

In [167]: # Mean

ar = np.array([2,4,5,6,8,9,1,3,7])
np.mean(ar)

Out[167]: 5.0

In [168]: # Variance

np.var(ar)

Out[168]: 6.666666666666667

In [169]: # Standard Deviation



np.std(ar)

Out[169]: 2.581988897471611

In [170]: # Square

np.square(ar)

Out[170]: array([ 4, 16, 25, 36, 64, 81, 1, 9, 49])

In [171]: # Power

np.power(ar,2)

Out[171]: array([ 4, 16, 25, 36, 64, 81, 1, 9, 49], dtype=int32)

In [173]: # Concat

ap = np.array([2,5,4,6,8,3])
newar = np.concatenate([ar,ap])
newar

Out[173]: array([2, 4, 5, 6, 8, 9, 1, 3, 7, 2, 5, 4, 6, 8, 3])

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 27/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [174]: # Flatten Ravel



arra = np.array([[1,2,3,4,5,6],[9,8,7,6,5,4]])
np.ravel(arra)

Out[174]: array([1, 2, 3, 4, 5, 6, 9, 8, 7, 6, 5, 4])

In [175]: # V-stack with 2-D iteration



age = np.array([9,8,7])
weight = np.array([1,2,5])
result = np.vstack([age,age,weight])

for i in result:
for j in i:
print(j)

result

9
8
7
9
8
7
1
2
5

Out[175]: array([[9, 8, 7],


[9, 8, 7],
[1, 2, 5]])

In [176]: # H-stack with 1-D iteration



age = np.array([9,8,7])
weight = np.array([1,2,5])
result = np.hstack([age,age,weight])

for i in result:
print(i)

result

9
8
7
9
8
7
1
2
5

Out[176]: array([9, 8, 7, 9, 8, 7, 1, 2, 5])

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 28/29
3/27/24, 7:43 PM PRAC-1 - Jupyter Notebook

In [ ]: ​

localhost:8888/notebooks/Documents/DataScienceFolders/PythonBasics/Home/PRAC-1.ipynb 29/29

You might also like