Python Part-1-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

Python-

Python is a high-level, interpreted, and general-purpose programming language

• Python is known for its simplicity, readability, and versatility, making it one of the most
popular programming languages in the world

Jupyter Notebooks
Jupyter notebooks are a powerful tool for interactive programming and data analysis. They
provide a convenient way to work with code, text, and visualizations all in one place. Here are
some essential keyboard shortcuts.

• Ctrl+Enter: Execute the current cell and stay on the same cell.
• Alt+Enter: Execute the current cell and move to the next cell.
• Shift+Enter: Execute the current cell and move to the next cell.
a=10
print('Namaste World')
print('This is Ismail')
print(type(a))
10

Namaste World
This is Ismail
<class 'int'>

10

Variables
In Python, variables are used to store data values. They act as containers to hold different types
of information, such as numbers, strings, lists, dictionaries, and more

variable_name = value

Here's an example of creating variables in Python:

# Integer variable
age = 30

# String variable
name = "Ismail"

# List variable
fruits = ['apple', 'banana', 'orange']
# Dictionary variable
person = {'name': 'Ismail', 'age': 21, 'occupation': 'Engineer'}

Variable names in Python should follow some rules:

1. They must start with a letter (a-z, A-Z) or an underscore (_).


2. The rest of the name can consist of letters, underscores, and numbers (0-9).
3. Variable names are case-sensitive (e.g., age and Age are different variables).
4. Avoid using reserved keywords (e.g., if, for, while, etc.) as variable names.
a=10
b=20
sum=a+b
print(sum)
print(a,b)

30
10 20

ac_c1= 10
#this is a comment
print(ac_c1)

10

Assigning Different type of data to a variable


variables are dynamically typed, which means you can reassign a variable to different types of
data at any point in your code.

a = 10
print(a) # Output: 10

a = 20
print(a) # Output: 20

a = "Hi, this is ismail"


print(a) # Output: Hi this is ismail

10
20
Hi, this is ismail

• The type() function is used to determine the type of an object in Python


• The id() function is used to get the unique identifier (memory address) of an object in
Python
print(a,type(a))
Hi this is ismail <class 'str'>

a=10
a=10
print(a,type(a))

10 <class 'int'>

a1 = 23
a2= 3.4
a3= 4+5j
print(a1,type(a1))
print(a2,type(a2))
print(a3,type(a3))

23 <class 'int'>
3.4 <class 'float'>
(4+5j) <class 'complex'>

• Each time we assign a new value to the variable a, it creates a new object and, hence, a
new memory address. As a result, the id() function will return different unique identifiers
for each value assigned to a.
a=4

print(id(a)) #unique identification number for that variable(meta)


a=5

print(id(a))

a=6
print(id(a))

140731876893576
140731876893608
140731876893640

a=10
b=10
print(id(a))
print(id(b))
# points to same value
# this optimmization only for -5 to 256

140732494111816
140732494111816

a=1000
b=1000
print(id(a))
print(id(b))
# for java/c++ some fixed memory for integer ex:4 bytes
# For python its different

a=10000000 #there is no limit to how big the variable is, it is up to


memory left

Arithmetic Operations
The basic arithmetic operations are:

• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Integer Division (//)
• Exponentiation (**)
• Modulus (%)
a=9
b=4
print(a+b)
print(a-b)
print(a*b)
print(a/b) # returns float
print(a//b) #integer division
print(a**b) #exponentiation
print(a%b) #remaindeer

13
5
36
2.25
2
6561
1

# Just put barckets to avoid unwanted behavior in calculations

2*3/4

1.5

2*(3//4)

(2*3)//4

1
## Simple Intrest
p=100
t=5
r=5
print((p*t*r)//100)

25

# fareheit to celcius
f=100
c=(f-32)*5/9
c

37.77777777777778

Input
a=input() #always takes as string
print(type(a),a)

<class 'str'> 5

a=float(input()) # input should be valid integer/float, otherwise


error
b=int(input()) # input should be valid integer, otherwise error
print(type(b))

c=a+b
print(c)

i = int(5.5)
print(i,type(i))

12
79

<class 'int'>
91.0
5 <class 'int'>

Boolean
a=True
b=False # capital
c="World"
type(b)

bool

Relational Operator
a=10
b=20
print(a>b)
print(a>=b)
print(a<=b)
print(a==b)
print(a!=b)

False
False
True
False
True

Logical Operators
a = 5>10
b = 4<5
c = False

r1 = a and b
r2 = a or b
r3 = not c

print(r1,r2,r3)

False True True

Conditional Operators
if a>b:
print("False")
else:
print("True")

#identation is very important

True
# even or odd
n= int(input())
if n%2==0:
print("Even")
else:
print("Odd")

5456

Even

Ternary operator syntax in python


n= int(input())
print("Even") if n%2==0 else print("Odd")

454561

Odd

a = int(input())
b = int(input())

if a>10 and b> 10:


print("True")
else:
print("False")

12
45

True

#finding largest of three

a= int(input())
b= int(input())
c= int(input())

if a>=b and a>=c:


print("max:",a)
elif b>=a and b>=c:
print("max:",b)
else:
print("max:",c)
45
45
41

max: 45

n= int(input())
if n> 10:
print("Red")
elif n>=5:
print("Green")
elif n>0:
print("Yellow")

45

Red

n= int(input())

if n>0:
print("Positive")
elif n<0:
print( "Negative")
else:
print( "Zero")

45

Positive

Nested Conditionals
n= int(input())
if n%2==0:
print("Even")
if n==0:
print("zero")
else:
print("Odd")

789

Odd
Loops
#first n natural numbers

n = int(input())
i=1
while i<=n:
print(i)
i+=1

1
2
3
4
5

#sum of n natural numbers

n = int(input())
sum=0
i=1
while i<=n:
sum+=i
i+=1
print(sum)

456

104196

#prime or not
import math
n = int(input())
i=2
istrue= True

while i <= math.sqrt(n):


if n%i ==0:
istrue= False
i+=1
if istrue:
print("Prime")
else:
print("Not Prime")

11

Prime
Nested While
# print all prime numbers between range 2,n
n = int(input())

i = 2

while i<=n:
istrue= True
j=2
while j <= math.sqrt(i):
if i%j ==0:
istrue= False
j+=1
if istrue:
print(i,"Prime")

i+=1

11

2 Prime
3 Prime
5 Prime
7 Prime
11 Prime

# farenheit to celcius in a range with step of w


s = int(input())
e = int(input())
w = int(input())

while s<=e:
print( (5*(s-32)) / 9)
s+=w

0
200
30

-17.77777777777778
-1.1111111111111112
15.555555555555555
32.22222222222222
48.888888888888886
65.55555555555556
82.22222222222223

n= int (input())

if n== 1:
a= int (input())
b= int (input())
print(a+b)
elif n == 2:
a= int (input())
b= int (input())
print(a-b)
elif n == 3:
a= int (input())
b= int (input())
print(a*b)
elif n == 4:
a= int (input())
b= int (input())
print(a//b)
elif n==5:
a= int (input())
b= int (input())
print(a%b)
else:
print ("Invalid Operation")

3
12
12

144

# reverse a number
n=int(input())
result=0
while n!=0:
l=n%10
result=result*10 + l
n=n//10
print(result)

449854896565

565698458944

# palindrome

# reverse the number and check


n=int(input())
temp=n
result=0
while n!=0:
last_digit=n%10
result=result*10 + last_digit
n=n//10

print("Palindrome") if result==temp else print("Not Palindeome")

123321

Palindrome

#sum of even digits and sum of odd digits of a number

n = int(input())

e = 0
odd = 0

while n != 0:
l = n % 10
if l % 2 == 0:
e += l
else:
odd += l
n = n // 10

print("even", e)
print("odd", odd)

123456

even 12
odd 9

# nth fibanocci using recurssion


def fib(n):
if n==1 or n==2:
return 1
else:
return fib(n-1) + fib(n-2)

n= int(input())
print(fib(n))

12

144

Patterns
# Steps to approach a pattern

# 1.No of rows
# 2.No of columns to print at generic ith row => can be a function of
n,i,j =>f(n,i,j)
# 3.What to print

# SQUARE PATTERN

n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print("*",end="") # print command go to next line
automatically
j+=1
print()
i+=1

*****
*****
*****
*****
*****

• some other patterns 1111 1234 4321

2222 1234 4321

3333 1234 4321

4444 1234 4321

n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(i,end="")
j+=1
print()
i+=1

1111
2222
3333
4444
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(j,end="")
j+=1
print()
i+=1

1234
1234
1234
1234

n=int(input())
i=1
while(i<=n):
j=n
while j>=1:
print(j,end="")
j-=1
print()
i+=1

4321
4321
4321
4321

# right angle triangle type


n=int(input())
i=1
while(i<=n):
j=1
while j<=i:
print(j,end="")
j+=1
print()
i+=1

1
12
123
1234
12345

# starts with row number


# i+j-1
n=int(input())
i=1
while(i<=n):
j=1
while j<=i:
print(i+j-1,end="")
j+=1
print()
i+=1

1
23
345
4567
56789

n=int(input())
i=1
k=1
while(i<=n):
j=1
while j<=i:
print(k,end=" ")
k+=1
j+=1
print()
i+=1

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Character Patterns
• In Python, adding a string and an integer together is invalid: str + int =
invalid.

• To get the ASCII value of a character, use the ord() function, but remember it works
for single characters only: ord('A').
• To get the character from its ASCII value, use the chr() function: chr(65) returns
'A'.

# A B C D E
n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(chr(ord('A') + j - 1),end=" ")
j+=1
print()
i+=1

A B C D E
A B C D E
A B C D E
A B C D E
A B C D E

n=int(input())
i=1
while(i<=n):
j=1
while j<=n:
print(chr(ord('A')+(i+j-1)-1),end=" ")
j+=1
print()
i+=1

A B C D E
B C D E F
C D E F G
D E F G H
E F G H I

n=int(input())
i=1

while(i<=n):
j=1
k=n-i+1
while j<=i:
print(chr(ord('A')+ k -1),end=" ")
k+=1
j+=1
print()
i+=1

F
E F
D E F
C D E F
B C D E F
A B C D E F

INVERTED PATTERNS
n=int(input())
i=1
while(i<=n):
j=1
while j<=(n-i+1):
print("*",end=" ")
j+=1
print()
i+=1

* * * * *
* * * *
* * *
* *
*

# n-i+1
n=int(input())
i=1
while(i<=n):
j=1
while j<=(n-i+1):
print(j,end=" ")
j+=1
print()
i+=1

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Reversed Pattern or Mirror Pattern
n=int(input())
i=1
while(i<=n):
s=1
while s<=(n-i):
print(" ",end="")
s+=1
j=1
while j<=(i):
print("*",end="")
j+=1
print()
i+=1

*
**
***
****
*****

Isoceles Pattern
n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1
# increasing sequence
j=1
while j<=i:
print(j,end="")
j+=1
k=1
j=j-1
# decreasing sequence
while k<=i-1:
j=j-1
print(j,end="")

k+=1
print()
i+=1
4

1
121
12321
1234321

n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1

# increasing sequence
j=1
while j<=i:
print(j+i-1,end="")
j+=1
k=1
j=j-1
j=j+i-1
# decreasing sequence
while k<=i-1:
j=j-1
print(j,end="")

k+=1
print()
i+=1

1
232
34543
4567654
567898765
67891011109876

n=int(input())
i=1
while(i<=n):
# Spaces
s=1
while s<=(n-i):
print(" ",end="")
s+=1
# increasing sequence
j=1
while j<=i:
print("*",end="")
j+=1
k=1
j=j-1
# decreasing sequence
while k<=i-1:
j=j-1
print("*",end="")

k+=1
print()
i+=1

*
***
*****
*******

n=int(input())
n1=(n+1)//2
n2=n1-1
i=1
while(i<=n1):
a=1
while(a<=n1-i):
print(" ",end="")
a=a+1
b=1
while(b<=2*i-1):
print('*',end="")
b=b+1
print()
i=i+1
i=n2
while(i>=1):
a=1
while(a<=n2 - i +1):
print(" ",end='')
a = a+1
j=1
while(j<=2*i-1):
print('*',end="")
j=j+1
print()
i = i-1
10

*
***
*****
*******
*********
*******
*****
***
*

For Loop and Range Method


• The for loop in Python is used to iterate over elements in a sequence, such as
strings, lists, tuples, dictionaries, sets, etc.

• The syntax of the for loop is:

for i in sequence:
# code block to execute for each element in the sequence

• The range() function is commonly used to generate a sequence of numbers. It has


the syntax:

range(start, stop, step)

where start is the starting value (inclusive), stop is the ending value (exclusive),
and step is the increment between values (equences for looping purposes.

for i in "Welcome to Our channel,This is Ismail Abilash":


print(i, end="")

Welcome to Our channel,This is Ismail Abilash

n= int(input())

for i in range(1,n+1,1):
print(i)

1
2
3
4
5
#single argument then it takes as end
n= int(input())
for i in range(n+1):
print(i)

0
1
2
3
4
5

#double argument then it takes as start,end


n= int(input())
for i in range(n+1,1):
print(i)

print(n)
for i in range(1,n+1):
print(i)

5
1
2
3
4
5

# numbers from n-1 to 0


# end should be -1, as it goes up to 1 only if given 0
n= int(input())
for i in range(n-1,-1,-1):
print(i)

4
3
2
1
0

# in range of a and b , print muliples of 3


# a<b

a=int(input())
b=int(input())
for i in range(a,b+1):
if i%3==0:
print(i)

1
12

3
6
9
12

# in range of a and b , print muliples of 3, with jump of 3


# a<b
a=int(input())
b=int(input())
s=0
if a%3==0:
s=a
elif a%3==1:
s= a+2
else:
s= a+1

for i in range(s,b+1,3):
print(i)

4
23

6
9
12
15
18
21

Wrong Syntax
for i in range(0.1, 0.4,0.1): range accepts only integer values

# Prime using for loop


# math.sqrt(n) gives float
import math
n =int(input())
prime = True
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
print("Not Prime")
prime = False
break
if prime:
print("Prime")

5461

Not Prime

# Pattern using for


n = int(input())

for i in range(1,n+1):
# spaces
for j in range(1, n-i+1):
print(" ", end="")

# increasing => i to 2*i-1


for k in range(i,2*i):
print(k, end="")

# decreasing => 2*i-2 to i


# i-1, i <----- 2*i-2
for l in range(2*i-2,i-1,-1):
print(l, end="")
print()

1
232
34543
4567654
567898765

Keywords in Python
1. break:
• Used to exit from a loop prematurely.
• Stops the current loop iteration and continues with the next statement after the loop.

2. continue:
• Skips the remaining code within the current loop iteration and starts the next iteration.
• Useful for excluding specific items from a loop.

3. pass:
• Acts as a null operation or a no-operation statement.
• Used as a placeholder when a statement is syntactically required but doesn't need to do
anything.

4. else with loops:


• The else clause can be used with loops to specify a block of code that should be executed
after the loop finishes normally (without encountering a break statement).
• The else block is executed only if the loop runs to completion without any break
statements.
# break: Terminating keyword
# if two looping statement if break is present in inner loop then
break can only break the
# inner execution only

# Prime using for loop


import math
n =int(input())
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
print("Not Prime")
break
else:
print("Prime")

2 7
3 7
4 7
5 7
6 7
Else statement

# else with while


a=2
b=7
while a<b:
print(a,b)
a+=1
else:
print("Else statement")

2 7
3 7
4 7
5 7
6 7
Else statement

# continue helps to skip


for i in range(1, 10):
if i%5==0:
continue
else:
print(i)

1
2
3
4
6
7
8
9

# in while, continue skips the increment, To solve: before continue do


the increment

# in c, c++,
# we can do this
# if(a>b){
# }

# in python we cant do like that


a=3
b=4
if a>b:
pass

# if we are not intrested in doing anything


# pass can be used in if,for, while

# pass is a dummy: like todo , todo in future

while i<=3:
pass
i+=1

for i in range(1,4):
pass

# Tems of Ap
# print first x terms of the series 3*N+2 which are not multiples of 4

x= int(input())
i=0
k=1

while i<=x:
if (3*k+2)% 4 != 0:
print(3*k+2)
i+=1
k+=1
5

5
11
14
17
23
26

# sum of numbers 1 to n
n= int(input())
sum=0
for i in range(1, n+1):
sum+=i

# product of numbers 1 to n
product =1
for i in range(1, n+1):
product*=i

print("Product",product)
print("Sum",sum)

Product 120
Sum 15

Strings and Lists


strings and lists are fundamental data structures used to store and manipulate data.

Strings
A string is a collection of characters, and it can be represented using either single quotes (' ') or
double quotes (" "). For example, a string can be "Namaste, World!" or 'Python Programming'.

Lists
A list is a collection of elements, and it can contain any combination of data types, including
other lists. Lists are enclosed in square brackets [ ] and can be accessed by their index. For
instance, a list could be [1, 2.2, 3, "apple", "banana"].

a="This is a string"
a='This is also a string'
a

'This is also a string'


c='a'
type(c) #there are no character type in python

str

a[0]

'T'

type(a[0])

str

# Strings are immutable


a="This is"
a[3]='a' # can't be changed

# string is immutable, variable is not


a="Other string"

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[121], line 3
1 # Strings are immutable
2 a="This is"
----> 3 a[3]='a' # can't be changed
5 # string is immutable, variable is not
6 a="Other string"

TypeError: 'str' object does not support item assignment

# To use "" in string use '' and for '' use ""
# we can use escape character \'

a='it\'s a googly'
a

"it's a googly"

# looping a string
a='it\'s a google product'

for i in a:
print(i,end="")

print()

for i in range(0,len(a)):
print(a[i],end="")
it's a google product
it's a google product

# Concatanate two strings


a="This is a"
b=" and This is b"

c= a+b

a= a+b

print(a)
print(c)

This is a and This is b


This is a and This is b

# string comparing
# Capital A to Z (65 to 90)
# Small a to z (97 to 122)
# 'Z' < 'a'
a='Z'
b='a'
print(a<b)

True

# split function to divide into parts

a="This is world of peace"


print(a.split()) #['This', 'is', 'a', 'is']

print(a.split("world"))

['This', 'is', 'world', 'of', 'peace']


['This is ', ' of peace']

# find: returns index of first occuring of string


# if no found, return -1
a.find("big")

# To returns the uppercase


a.upper()
print(a)

# we can do to change the a


a= a.upper()
print(a)
This is big string with is random words
THIS IS BIG STRING WITH IS RANDOM WORDS

# lower
a= a.lower()
print(a)

this is big string with is random words

# islower
print(a.islower())

True

# isupper
print(a.isupper())

False

# startswith
print(a.startswith("th"))
print(a.endswith("th"))

True
False

# substring in python :slicing


# a[si:ei] : si is included and ei is not included

a= "this is a new string"


a[2:5]

'is '

a[2:] #starting from 2 to end

'is is a new string'

a[:4]

'this'

a[:]

'this is a new string'

a[2:13:2]

'i sanw'

# ---->end<-----
# end-1 end+1
a[18:2:-1] # up to 3 reverse
'nirts wen a si s'

# replace first occurance of a with b


s=input()
a='x'
b='y'

index= s.find(a) #first occurence of a's index

if p!=-1:
ans= s[:index]+b+s[index+1:]
ans

expressxerox

'eypressxerox'

# replace all occurances


# approach1: use find() replace up to find gives -1

ans=input()

a='x'
b='y'

for i in range(0,len(ans)):
if ans[i]==a:
ans = ans[:i]+b+ans[i+1:]
ans

codex

'codey'

# inbuilt function of repalce: it returns the new string


s=s.replace('x','y')
s

'eypressyeroy'

# replace :not changed the orginal string , returns the new string

a="This is big string with is random words"


print(a)

print(a.replace("is", "are")) #replace all occurences, even in words,


and returns

print(a)
This is big string with is random words
Thare are big string with are random words
This is big string with is random words

"abc"[:2]

'ab'

str1="hello"
str1[-1] #same
str1[-1:] #same

'o'

s="abcdefghi"
s[-3:-1]

'gh'

Lists in Python:
• Collection of elements, no need to predefine size or data type.
• Dynamic in size: can grow or shrink as needed.
• Stores various data types.
• Efficiently allocates space and resizes when necessary.
• internally list allocates some space, if we ask more , it will copy the elements to new list
with additional storage and returns it

List Methods
Python provides several built-in methods to perform operations on lists. Some commonly used
list methods include:

• append(element): Adds an element to the end of the list.


• insert(index, element): Inserts an element at the specified index.
• remove(element): Removes the first occurrence of the specified element from the list.
• pop(index): Removes and returns the element at the specified index.
• len(list): Returns the number of elements in the list.
# both are same
a=[1,2,3]
b=list([3,4,6])
print(a)
print(b)

[1, 2, 3]
[3, 4, 6]

[] #empty list

[]
a=[1,2,"abc",5+3j]
a

[1, 2, 'abc', (5+3j)]

# list of lists is possibles


a=[[1,2,3],5]
a

[[1, 2, 3], 5]

# loop with list

b= [ 0 for i in range(0,10)]
print(b)

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

b= [ i for i in range(0,10)]
print(b)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

b= [ i for i in "ismail"]
print(b)

['i', 's', 'm', 'a', 'i', 'l']

b= [ i*i for i in range(0,10) ]


print(b)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# length of string

a=[1,2,4,5,6]
print(len(a))

# adding two lists

b=[6,7,8]
a=a+b

print(a)

[1, 2, 4, 5, 6, 6, 7, 8]

a=[1,3,5]
b=[6,7,8]
c=a+b
print(c)

[1, 3, 5, 6, 7, 8]

c+3 #not possible

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[184], line 1
----> 1 c+3 #not possible

TypeError: can only concatenate list (not "int") to list

a*b #not possible

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[185], line 1
----> 1 a*b

TypeError: can't multiply sequence by non-int of type 'list'

a*3 #possible
# copies 3 times and gives new

[1, 3, 5, 1, 3, 5, 1, 3, 5]

# add to end
a.append(4)
print(a)

[1, 3, 5, 4]

# add data at specific index


a.insert(0,10) #index, vlaue
print(a)

[10, 1, 3, 5, 4]

# add b to a
a.extend(b) # a=a+b
print(a)

[10, 1, 3, 5, 4, 6, 7, 8]

# remove "data"
a.remove(7)
a
[10, 1, 3, 5, 4, 6, 8]

# remove from particular index, removes and returns the popped value
a.pop(0)
print(a)

[1, 3, 5, 4, 6, 8]

del a[4] #doesnt return the deleted value

del a[1]
a

[1, 5, 4, 8]

Sort
The list.sort() method is a built-in method available for lists in Python. It sorts the elements of
the list in place, which means it modifies the original list directly without creating a new one.

• Here's the syntax of the list.sort() method: list.sort(key=None,


reverse=False)

• if reverse=True, then sorts in descending order

max,min
• min() and max() are built-in functions used to find the minimum and maximum
elements, from an iterable or a set of arguments.

• Both functions work on various data structures like lists, tuples, strings, and other
iterables.

• min(iterable, *args, key=None, default=None)

• max(iterable, *args, key=None, default=None)

list should be homogenous

a=[10, 1, 3, 5, 4, 6, 7, 8]
a.sort() #orginal list sorted
print(a)

[1, 3, 4, 5, 6, 7, 8, 10]

b=[1,3,5,7,9,8,5,4,2,1]
print(max(b))

The in operator is a built-in operator in Python used to check for membership in a sequence or
container
100 in a

False

print([i.lower() for i in "HELLO"])

['h', 'e', 'l', 'l', 'o']

a.pop() #if index not given, removes the last one

10

Taking input into List


# Pattern 1
# 5 n
# 1
# 4
# 5
# 5
# 8

n=int(input())
a=[]
for i in range(n):
s= int(input())
a.append(s)
a

5
1
4
5
5
8

[1, 4, 5, 5, 8]

## 5
# 1 2 3 4 5

n=int(input())
a=input().split(" ")

s=[]

for i in a:
s.append(int(i))

s
5
1 2 3 4 5

[1, 2, 3, 4, 5]

# more optimized way


n=int(input())
a=input().split()

s=[int(i) for i in a]
s

5
1 2 2 4 5

[1, 2, 2, 4, 5]

# more more optimized way


# 5
# 1 2 3 4 5
n=int(input())

s=[int(i) for i in input().split()]


s

5
1 2 3 4 5

[1, 2, 3, 4, 5]

## 5 1 2 3 4 5

s=[int(i) for i in input().split()]


n=s.pop(0) #pass the index
print(n,s)

# difference of even sum and odd sum

l=[int(i) for i in input().split()]

even=0
odd=0

for i in l:
if i%2 == 0:
even+=i
else:
odd+=i
print(even-odd)

12 3 4 5
8

# swapping adjacent places

l=[int(i) for i in input().split()] #input

length= len(l)

for i in range(0,length,2):
if i< length-1:
l[i],l[i+1]= l[i+1],l[i]

for i in l:
print(i,end="")

1 2 3 4 5 678

21436785

List in Python
List slicing in Python allows you to extract a portion of a list by specifying start, stop, and step
parameters. The syntax for list slicing is as follows:

new_list = list_name[start:stop:step]

Where:

• start: The index where the slice begins (inclusive). If omitted, the slicing starts from the
beginning of the list (index 0).
• stop: The index where the slice ends (exclusive). If omitted, the slicing goes until the end
of the list.
• step: The step size or increment. If omitted, the default value is 1, which means
consecutive elements will be included in thd = 4 print(my_list[start:end]) # Output: [2, 3,
4] ```

Keep in mind that list slicing does not modify the origina

l list; it creates a new list containing the sliced elements. Also, if the start index is greater than
the stop index, or the step is negative, the slice will return an empty list.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Basic slicing
print(my_list[2:6]) # Output: [3, 4, 5, 6]
print(my_list[:5]) # Output: [1, 2, 3, 4, 5]
print(my_list[5:]) # Output: [6, 7, 8, 9, 10]
print(my_list[:]) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (a
copy of the entire list)
# Slicing with step
print(my_list[::2]) # Output: [1, 3, 5, 7, 9] (every second
element)
print(my_list[1::3]) # Output: [2, 5, 8] (every third element
starting from index 1)
print(my_list[::-1]) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(reversed list)

# Negative indexing
print(my_list[-3:]) # Output: [8, 9, 10] (last three elements)
print(my_list[:-3]) # Output: [1, 2, 3, 4, 5, 6, 7] (all elements
except the last three)

# Slicing with variables


start = 1
end = 4
print(my_list[start:end]) # Output: [2, 3, 4]

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

print(my_list)
my_list.reverse()
my_list

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

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

Multidimensional Lists
In Python, there is nothing specifically called a "multidimensional list." However, we can
represent multidimensional structures using lists of lists. One common example is a 2D list (m x
n), which is essentially a list of lists where each sub-list represents a row or a 1D array.

A 2D list can be created as follows:

two_dimensional_list = [
[element_00, element_01, element_02, ..., element_0n],
[element_10, element_11, element_12, ..., element_1n],
...
[element_m0, element_m1, element_m2, ..., element_mn]
]

Here:

• m represents the number of rows (sub-lists).


• n represents the number of columns (elements in each sub-list).

The two_dimensional_list can be visualized as an m x n matrix.

While working with more dimensions, the concept remains the same, and you can nest
additional lists to create 3D or higher-dimensional arrays. However, as the dimensionality
increases, it becomes more complex, and using specialized libraries like NumPy for handling
multidimensional arrays becomes more efficient and convenient.

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

print(matrix[1][2]) # Output: 6 (element in the 2nd row, 3rd column)

print(len(matrix)) #no of rows


print(len(matrix[0])) #no of columns

6
3
3

Taking Input into MULTIDIMENSIONL LIST


Different methods to take input into a multidimensional list in Python.

Method 1:
This method takes input in a specific format where the first line contains two space-separated
integers m and n, followed by m * n space-separated integers representing the elements of the
2D lis oose any of them based on your preference and the input format you want to use.

m, n = map(int, input().split())

l = []

for i in range(m):
next_row = [int(i) for i in input().split()]
l.append(next_row)
print(l)
# Input:
# 2 3
# 1 2 3
# 4 5 6

# Output:
# l = [[1, 2, 3], [4, 5, 6]]

2 3
1 2 3
4 5 6

[[1, 2, 3], [4, 5, 6]]

Method 2:
This method is similar to Method 1, but it uses nested loops to take input for each element of the
2D list.

m, n = map(int, input().split())
l = []

for i in range(m):
next_row = []
for j in range(n):
next_row.append(int(input()))
l.append(next_row)

print(l)

# Input:
# 2 3
# 1
# 2
# 3
# 4
# 5
# 6

# Output:
# l = [[1, 2, 3], [4, 5, 6]]

2 3
1
2
3
4
5
6
[[1, 2, 3], [4, 5, 6]]

Method 3:
This method takes input in the same format as Method 1 but uses list slicing to construct the 2D
list.

m, n = map(int, input().split())
l = [int(i) for i in input().split()]
ol = []

for i in range(m):
start_index = n * i
end_index = n * (i + 1) # excludes kabbati
next_row = l[start_index:end_index]
ol.append(next_row)

print(ol)

# Input:
# 2 3
# 1 2 3 4 5 6

# Output:
# ol = [[1, 2, 3], [4, 5, 6]]

2 3
1 2 3 4 5 6

[[1, 2, 3], [4, 5, 6]]

# diagnol of 2d matrix
a=[[1,2,3],[4,5,6],[7,8,9]]

print([a[i][i] for i in range(len(a))])

[1, 5, 9]

More on Multi dimensional lists


The general syntax for slicing a 2D list is the same as for a 1D list. You specify the start and stop
indices for each dimension within the square brackets separated by commas. Remember that
the stop index is exclusive, meaning it won't include the element at that index in the slice.

Keep in mind that slicing creates new lists containing the sliced elements and doesn't modify the
original list.
List comprehension
List comprehension is a concise way to create lists in Python. It provides a compact and readable
syntax for generating new lists from existing ones, applying transformations, and filtering
elements based on specific conditions. List comprehension is a powerful feature in Python that
allows you to write elegant and efficient code.

The basic syntax of list comprehension is as follows:

new_list = [expression for item in iterable if condition]

Where:

• expression: The expression to be applied to each item in the iterable.


• item: A variable that represents the current item in the iterable.
• iterable: The data source (e.g., list, tuple, string, etc.) from which you want to create
the new list.
• if condition (optional): A condition that filters elements based on certain criteria. It's
not required for all list comprehensions.

List comprehensions are concise and often more readable than writing equivalent code using
traditional loops. They are widely used in Python and are considered one of the "Pythonic" ways
to create and manipulate lists. However, it's essential to use them judiciously to maintain code
clarity and readability.

# Example 2D list (3x3)


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

# Slicing rows
row_slice = matrix[1:3] # Rows 2 and 3
print(row_slice)
# Output: [[4, 5, 6], [7, 8, 9]]

# Slicing columns (using list comprehension)


column_slice = [row[1] for row in matrix] # Column 2
print(column_slice)
# Output: [2, 5, 8]

# Slicing a sub-region (using list comprehension)


sub_slice = [row[1:3] for row in matrix[1:3]] # Rows 2 and 3, Columns
2 and 3
print(sub_slice)

# Output: [[5, 6], [8, 9]]


[[4, 5, 6], [7, 8, 9]]
[2, 5, 8]
[[5, 6], [8, 9]]

# some examples of list comprehension:

# 1. Creating a list of squares from 1 to 5:

squares = [x**2 for x in range(1, 6)]


print("Squares:",squares)
# Output: [1, 4, 9, 16, 25]

# 2. Filtering even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = [x for x in numbers if x % 2 == 0]
print("Even Numbers:",even_numbers)
# Output: [2, 4, 6, 8, 10]

# 3. Generating a list of tuples containing numbers and their squares:

numbers = [1, 2, 3, 4, 5]
number_squares = [(x, x**2) for x in numbers]
print("number squares:",number_squares)
# Output: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

# 4. Extracting lowercase characters from a string:


sentence = "Hello World"
lowercase_chars = [char for char in sentence if char.islower()]
print("lowercase chars:",lowercase_chars)
# Output: ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']

Squares: [1, 4, 9, 16, 25]


Even Numbers: [2, 4, 6, 8, 10]
number squares: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
lowercase chars: ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']

a=[[i,2*i] for i in range(5)]


a

[[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]

a=[ [ i*j for j in range(15) ] for i in range(5)]


a

[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28],
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42],
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56]]

# print column wise sum


a=[ [ i*j for j in range(5) ] for i in range(5)]
m= len(a)
n= len(a[0]) #check if a is empty before doing this
# dont use sum as a variable name, it overshadows and we cant use
sum() function in our code
for i in range(n):
s=0
for j in range(m):
s+=a[j][i]
print(s)

0
10
20
30
40

# Row wise sum in multidimensional array


a=[ [ i*j for j in range(5) ] for i in range(5)]
m= len(a[0])
n= len(a)
for i in range(m):
s= 0
for j in range(n):
s+=a[i][j]
print(s)

0
10
20
30
40

a=[1,2,3,4,[56]]
b=list(a)
a[0] = 5
a[4][0]=3
print(b)

# They only create a copy on the 0th level . Thats called shallow
copy. The elements of a nested
# elements are copied by reference

[1, 2, 3, 4, [3]]

# check if string is a palindrome or not


# no reverse method on string
a="malayalam"
b=a[::-1] #reverse
if a==b:
print("Palindrome")
else:
print("Not a Palindrome")

Palindrome

print("".join(reversed("Hello World")))

dlroW olleH

a=reversed("Hello World") #revesed


print(type(a))
for i in a:
print(type(i))

<class 'reversed'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

# Print all Sub Strings

a= "Albr"

for i in range(len(a)):
s=""
for j in range(i,len(a)):
s+=a[j]
print(s)

A
Al
Alb
Albr
l
lb
lbr
b
br
r

# Array equilibrium index


# Equilibrium Index of an array/list is an index 'i' such that the sum
of elements at indices [0 to (i - 1)] is equal to the sum of elements
# at indices [(i + 1) to (N-1)].
# The item at the index 'i' is not included in either part.
# If more than one equilibrium indices are present, then the index
appearing first in left to right fashion should be returned.

array = [1, 4, 9, 3, 2]

found_equilibrium = False

for i in range(len(array)):
left_sum = sum(array[0:i])
right_sum = sum(array[i+1:])
if left_sum == right_sum:
print(i)
found_equilibrium = True
break

if not found_equilibrium:
print(-1)

a=[ [ i*j for j in range(5) ] for i in range(5)]


a

[[0, 0, 0, 0, 0],
[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8],
[0, 3, 6, 9, 12],
[0, 4, 8, 12, 16]]

# Wave print: print first column top to bottom and 2nd column bottom
to top , repeat this

isdown= True

for i in range(5):
if isdown:
for j in range(0,5):
print(a[j][i],end=" ")
print()
isdown=False
else:
for j in range(4,-1,-1):
print(a[j][i],end=" ")
print()

0 0 0 0 0
4 3 2 1 0
8 6 4 2 0
12 9 6 3 0
16 12 8 4 0

Functions
Functions are blocks of reusable code that perform specific tasks. Functions help in organizing
code, making it modular, and improving code readability. They allow you to break down complex
problems into smaller, manageable parts, making the code easier to maintain and understand.

def function_name(parameter1, parameter2, ...):


# Function body
# Code to perform a specific task
# Return statement (optional)

In Python, functions are blocks of reusable code that perform specific tasks. Functions help in
organizing code, making it modular, and improving code readability. They allow you to break
down complex problems into smaller, manageable parts, making the code easier to maintain
and understand.

To define a function in Python, you use the def keyword, followed by the function name, a list of
parameters (if any), and a colon (:). The function body is indented, and it contains the code that
will be executed when the function is called.

Here's the basic syntax for defining a function:

def function_name(parameter1, parameter2, ...):


# Function body
# Code to perform a specific task
# Return statement (optult = square(4)
print(result) # Output: 16

In Python, functions are first-class citizens, which means you can pass functions as arguments to
other functions, return functions from functions, and store functions in variables or data
structures. This capability is essential for functional programming and enables powerful
programming paradigms.) `

# nCr =n!/(n-r)!*r!

# def name(arguments/inputs)

def factorial(a):
fact=1
for i in range(1,a+1):
fact= fact*i
return fact

n= int(input())
r= int(input())

print("The nCr is ",factorial(n)//(factorial(n-r) * factorial(r)) )

10
2

The nCr is 45

def greet(name="Telangana"):
return f"Hello, {name}!"

print(greet())

Hello, Telangana!

Why we need functions


1.Avoid repititons

2.Readable

3.Testing become easy

import math

# prime function
def isPrime(a):
for i in range(2,int(math.sqrt(a))+1):
if a%i==0:
break
else:
return True
return False

isPrime(100)

False

import math

# prime all primes i the 2 to N


def PrintPrimes2ToN(n):
for i in range(2,n+1):
if isPrime(i):
print(i)

PrintPrimes2ToN(20)

2
3
5
7
11
13
17
19

def ncr(n,r):
return factorial(n)//(factorial(n-r) * factorial(r))

ncr(5,4)

# How Function call Works

# D
# C
# B
# A

# callstack first called will complete at last


# variables stores in its execution context

def A():
print('A starts')
print('A ends')

def B():
print('B starts')
A()
print('b ends')

def C():
B()
print('C starts ')
print('C ends ')

C()

B starts
A starts
A ends
b ends
C starts
C ends

# Functions using variables,Strings and Lists

def increment(i):
i= i+1
print("in function,",i)

k=10
increment(k)
print("outside function",k)

in function, 11
outside function 10

# using list
# changes effects the orginal
# pointer stores reference

# this cant happen for string


def increment(l):
l[0]= l[0]+1
print("in function,",l)

a=[2,3,4]

increment(a)
print("outside function",a)

in function, [3, 3, 4]
outside function [3, 3, 4]

# change list
# pointer stores reference, completly changing to other list
def increment(l):
l=[0,8]
print("in function,",l)

a=[2,3,4]

increment(a)
print("outside function",a)

in function, [0, 8]
outside function [2, 3, 4]

# string, strings are immutable


def increment(s):
s="abc"
print("inide function:",s)
a="def"

increment(a)
print("outside function:",a)

inide function: abc


outside function: def

# return a list from function

def create_n_array(n):
l=[ i for i in range(n,0,-1)]
return l

print(create_n_array(5))

[5, 4, 3, 2, 1]

# Swap alternate elements of a list

n=int(input())
l=[ i for i in range(n)]

length = (len(l)-1) if (len(l)%2==0) else (len(l)-2)

for i in range(0,length,2):
l[i],l[i+1]=l[i+1], l[i]

10

[1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# other approach

n=int(input())
l=[ i for i in range(n,0,-1)]

i=0
while i+1 < len(l):
l[i],l[i+1]=l[i+1], l[i]
i= i+2
l

10

[9, 10, 7, 8, 5, 6, 3, 4, 1, 2]
Variable Scope in Python
In Python, variables can have different scopes, which determine where the variable is accessible
and how long it exists. There are two main types of variable scope:

1. Local Variables: These variables are defined inside a function and are only
accessible within that function. They are created when the function is called and
exist as long as the function is executing.

2. Global Variables: These variables are defined outside any function and are
accessible throughout the entire program. They are created when the program
starts and exist until the program he function will result in an error.

a1= 10 #global variable

def f1():
b1 =12 #local variable
print(a1) #global variable is acessible here
print(b1)

print(a1)
f1()
print(b1) #cannot print a local variable outside a function

10
10
12

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[50], line 10
8 print(a1)
9 f1()
---> 10 print(b1) #cannot print a local variable outside a function

NameError: name 'b1' is not defined

def f1():
b1 =12 #local variable
print(a1) #a1 can be called, even a1 is defined after function but
it should be defined before the function call
print(b1)
# print(c3) #cant accessible, c2 is defined after function call

a1= 10 #global variable


print(a1)
f1()
c3=20 #global variable
10
10
12

a4 = 13

def f4():
a4=12 #acess is fine but when you try to change, python assumes
you want to create a variable
print(a4)

print(a4) #13
f4()
print(a4)

13
12
13

a4 = 13

def f4():
global a4 #this is syntax, dont assign in this statement
a4 =12 #if you want use global, we explicitly specify global
print(a4)

print(a4) #13
f4()
print(a4)

13
12
12

# Default Parameters
# ex: print("abc")
# ex: print("abc",end="")

# arguments order:
# non default, default

def sum_of_numbers(a,b,c=0,d=0): #dont write functions with keywords


like sum,max,min
return a+b+c+d
sum_of_numbers(4,5,6)

15

sum_of_numbers(b=8,a=5,d=56)

69
# must pass default arguments by specifying or normal passing
sum_of_numbers(3,4,d=7)

14

# Farenheit to celcius
# s,e.w
def f_to_c(f):
return (f-32)*5//9

s=int(input())
e=int(input())
w=int(input())

for i in range(s,e+1,w):
print(i," ",f_to_c(i))

50
300
20

50 10
70 21
90 32
110 43
130 54
150 65
170 76
190 87
210 98
230 110
250 121
270 132
290 143

# check whether is member of fibanocci or not

def check_fibanocci(n):
if n==1:
return True
past=1
curr=1
i=1
while i<n:
future = past+curr
past =curr
curr=future
i=future
if i== n:
return True
else:
return False
# if returns not works then else works

check_fibanocci(3)

True

Tuples
• Tuples are similar to list but not same
• Tuples are enclosed in parentheses ( ).
• Tuples are immutable, while lists are mutable.
• Elements in a tuple can be accessed using indexing.
• Tuples can be unpacked into multiple variables.
• Commonly used for returning multiple values from functions.
• Tuples can be used as keys in dictionaries due to their immutability.
• To create a single-element tuple, use a trailing comma after the element: (42,).
• Useful for representing fixed collections of elements.
a=[1,2] #list
b=(1,2) #tuple

c,d =1,2 #assignment :same as below


c,d =b #assignment,unpacking into variables

print(c,d)

e=1,2 #when you keep multiple things into a single thing, python makes
it a tuple

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

1 2
<class 'list'>
<class 'tuple'>
<class 'int'>
<class 'int'>
<class 'tuple'>

# Acess elements in tuple: it is just like list

# the indexing and slicing works same way for strings, tuples and
lists
# Tuples are also ordered

a=(1,2,4,7,8,9)
a[0]
a[1:3]
a[1:]

(2, 4, 7, 8, 9)

a=(1,2,4,7,8,9)
a[0]=1

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[69], line 2
1 a=(1,2,4,7,8,9)
----> 2 a[0]=1

TypeError: 'tuple' object does not support item assignment

a=(1,2,4,7,8,9)
a=(4,5) #this is possible
a=(1,2,4,7,8,9,1,3,5)

del a[3] #not possible

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[71], line 1
----> 1 del a[3] #not possible

TypeError: 'tuple' object doesn't support item deletion

Functions in tuples
Python provides several built-in functions that you can use with tuples. Here are some of the
most commonly used built-in functions on tuples:

1. len(tuple): Returns the number of elements in the tuple.

2. tuple(iterable): Converts an iterable (e.g., list, string) into a tuple.

3. max(tuple): Returns the maximum element in the tuple.

4. min(tuple): Returns the minimum element in the tuple.

5. sum(tuple): Returns the sum of all elements in the tuple (works only with
numeri,atleast comparablesc elements).
6. tuple.count(element): Returns the number of occurrences of a specific element
in the tuple.

7. tuple.index(element): Returns the index of the first occurrence of a specific


element lculations on tuples in Python.

my_tuple = (1, 2, 3, 4, 5, 2)

# Using built-in functions


print(len(my_tuple)) # Output: 6
print(max(my_tuple)) # Output: 5
print(min(my_tuple)) # Output: 1
print(sum(my_tuple)) # Output: 17
print(my_tuple.count(2)) # Output: 2 (2 occurs twice)
print(my_tuple.index(3)) # Output: 2 (index of the first
occurrence of 3)

6
5
1
17
2
2

1 in a #membership checking

True

# adding two tuples


a=(1,2,3)
b=(4,5,6)
c=a+b
c

(1, 2, 3, 4, 5, 6)

# tuple of tuples
d =(a,c)
d

((1, 2, 3), (1, 2, 3, 4, 5, 6))

e=a*2 # copies 2 times


e

(1, 2, 3, 1, 2, 3)

a=("ab","bc","de")
min(a)

'ab'
# list to tuple
l=[1,2,3]
t=tuple(l)
t

(1, 2, 3)

# Variable length input and Output


# sum2(.................) multiple

# variable length input to function

def sum2(a,b,*more):
print(type(more))
ans=a+b
for i in more:
ans+=i
return ans

print("Sum is ",sum2(10,4,6,10,20))

<class 'tuple'>
Sum is 50

# variable length output from function


def sum_diff(a,b):
return a+b,a-b
c=sum_diff(4,5)
print(c)

d,e= sum_diff(10,5) #length has to match


print(d)
print(e)

(9, -1)
15
5

Dictionary
• In Python, a dictionary is a data structure that stores a collection of key-value pairs.
• It is also known as an associative array or a hash map in other programming languages.
• Dictionaries are unordered, mutable, and indexed by unique keys.

Here's the basic syntax of a dictionary:

my_dict = {
key1: value1,
key2: value2,
...
}

• key1, key2, ...: Unique keys used to access the corresponding values.
• value1, value2, ...: Values associated wi related data.

Some of the most commonly used inbuilt methods for dictionaries in Python include:

1. dict.get(key, default): Returns the value associated with the specified key. If
the key is not found, it returns the specified default value (if provided) or None.

2. dict.keys(): Returns a view of all the keys in the dictionary.

3. dict.values(): Returns a view of all the values in the dictionary.

4. dict.items(): Returns a view of all the key-value pairs in the dictionary as tuples.

5. dict.update(other_dict): Updates the dictionary with the key-value pairs from


another dictionary.

6. dict.pop(key, default): Removes the key and its associated value from the
dictionary. If the key is not found, it returns the specified default value (if provided)
or raises a KeyError.

7. dict.popitem(): Removes and returns the last key-value pair (in Python 3.7+).

8. dict.clear(): Removes all key-value pairs from the dictionary, making it empty.

9. len(dict): Returns the number of making it easy to manipulate and access data in
the dictionary.

my_dict = {
'name': 'Ismail abi',
'age': 30,
'city': 'New York'
}

# Using inbuilt methods


print(my_dict.get('name',"name")) # Output: 'John'
print(my_dict.keys()) # Output: dict_keys(['name', 'age',
'city'])
print(my_dict.values()) # Output: dict_values(['John', 30, 'New
York'])
print(my_dict.items()) # Output: dict_items([('name', 'John'),
('age', 30), ('city', 'New York')])

my_dict.update({'country': 'USA'})
print(my_dict) # Output: {'name': 'John', 'age': 30,
'city': 'New York', 'country': 'USA'}
my_dict.pop('age',0)
print(my_dict) # Output: {'name': 'John', 'city': 'New
York', 'country': 'USA'}

my_dict.clear()
print(my_dict) # Output: {}

Ismail abi
dict_keys(['name', 'age', 'city'])
dict_values(['Ismail abi', 30, 'New York'])
dict_items([('name', 'Ismail abi'), ('age', 30), ('city', 'New
York')])
{'name': 'Ismail abi', 'age': 30, 'city': 'New York', 'country':
'USA'}
{'name': 'Ismail abi', 'city': 'New York', 'country': 'USA'}
{}

# we give key value pair

a={
"the":2,
"a":5
}
print(type(a))

b= {
100:"the",
}
print(b)

<class 'dict'>
{100: 'the'}

# for lists, 10000 index means you need to have atleast 1000
# but for dictionary it is not, it is still 1
len(b)

b=a.copy()
print(b)

{'the': 2, 'a': 5}

c=dict([("the",3),
("and",6)]
)
print(c)

{'the': 3, 'and': 6}
d = dict.fromkeys(["abc",32,5], 10) #if you dont provide, then None
d

{'abc': 10, 32: 10, 5: 10}

a={
1:2,
3:4,
"list":[1,23],
"dict":{
1:1,
2:3,
4:5}
}
print(a)

{1: 2, 3: 4, 'list': [1, 23], 'dict': {1: 1, 2: 3, 4: 5}}

# acessing

a[1] # use keys for acessing

a["list"]

[1, 23]

print(a.get("l")) # If the key is not found, it returns the specified


default value (if provided) or None.

None

a.get("li",0) #we can give defalt value to return if not found

a.keys() #behaves like list

dict_keys([1, 3, 'list', 'dict'])

a.values()

dict_values([2, 4, [1, 23], {1: 1, 2: 3, 4: 5}])

a.items() #list of tuples

dict_items([(1, 2), (3, 4), ('list', [1, 23]), ('dict', {1: 1, 2: 3,


4: 5})])

for i in a:
print(i) #keys
1
3
list
dict

for i in a:
print(i,":",a[i]) #keys

1 : 2
3 : 4
list : [1, 23]
dict : {1: 1, 2: 3, 4: 5}

for i in a.values():
print(i)

2
4
[1, 23]
{1: 1, 2: 3, 4: 5}

# membership operator to chck whether key exist or not


"list" in a #checks only keys

True

"li" in a

False

# Adding or updating Data in Dictionary


a["78"]="345"

{1: 2, 3: 4, 'list': [1, 23], 'dict': {1: 1, 2: 3, 4: 5}, '78': '345'}

a["abc"]="def" #adding data

{1: 2,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'def'}

# updating
a["abc"] ="hik"

a
{1: 2,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'hik'}

# update
b={1:100,"aas":"fd"}
a.update(b) #what ever the values of b not available in a, will be
added
# what ever keys available in both a and b, value will be according to
b

{1: 100,
3: 4,
'list': [1, 23],
'dict': {1: 1, 2: 3, 4: 5},
'78': '345',
'abc': 'hik',
'aas': 'fd'}

# remove
a.pop('as',0) #key required, if not found gives error, give default
value to avoid

del a[1]

{3: 4, 'list': [1, 23], 'dict': {1: 1, 2: 3, 4: 5}, '78': '345',


'abc': 'hik'}

a.clear()

{}

# Print all words with frequency k

def Print_allWordWithFrequencyk(s,k):
l= s.split()
d={}

for i in l:
d[i] = d.get(i,0)+1
for i in d:
if d[i]==k:
print(i)

s="This is a good a of is of are are"

Print_allWordWithFrequencyk(s,1)

This
good

Sets in Python
• A set is a collection of unique elements, where each element is unique and unordered.
• Sets are useful for eliminating duplicates from a collection and performing set
operations like union, intersection, and difference.
my_set = {element1, element2, ...}

• element1, element2, ...: Unique elements that make up the set.

• Sets are defined using curly braces {}, but be cautious because using empty curly
braces will create an empty dictionary, not an empty set.

• To create an empty set, use the set() constructor.


• collection of unique elements with no ordering
a={"apple","banana",23}
a

{23, 'apple', 'banana'}

type(a)

set

a[0] #not valid

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[69], line 1
----> 1 a[0] #not valid

TypeError: 'set' object is not subscriptable

a['abc'] #not valid


----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
Cell In[70], line 1
----> 1 a['abc'] #not valid

TypeError: 'set' object is not subscriptable

'abc' in a

False

23 in a

True

for i in a:
print(i)

banana
apple
23

len(a)

Functions in sets
1. set(): Creates an empty set.

2. len(set): Returns the number of elements in the set.

3. add(element): Adds a single element to the set.

4. update(iterable): Adds multiple elements from an iterable to the set.

5. remove(element): Removes the specified element from the set. Raises a KeyError
if the element is not found.

6. discard(element): Removes the specified element from the set (if it exists). Does
not raise an error if the element is not found.

7. pop(): Removes and returns an arbitrary element from the set. Raises a KeyError
if the set is empty.

8. clear(): Removes all elements from the set, making it empty.

9. copy(): Returns a shallow copy of the set.

10. union(other_set), |: Returns a new set containing all elements from both sets
(elements are unique).
11. intersection(other_set), &: Returns a new set containing common elements
between both sets.

12. difference(other_set), -: Returns a new set containing elements that are in the
first set but not in the second set.

13. symmetric_difference(other_set), ^: Returns a new set containing elements


that are in either of the sets but not in both.

14. issubset(other_set): Returns True if the set is a subset of the specified set,
otherwise False.

15. issuperset(other_set): Returns True if the set is a superset of the specified set,
otherwise False.

Additional functions
Here are additional functions and methods on sets, including a.intersection_update(b),
a.difference_update(b), a.symmetric_difference_update(b), and
a.isdisjoint(b):

1. a.intersection_update(b): Updates the set a with the intersection of sets a and


b, keeping only the elements that are common to both sets.

2. a.difference_update(b): Updates the set a by removing the elements present in


set b from set a.

3. a.symmetric_difference_update(b): Updates the set a with the symmetric


difference of sets a and b, keeping only the elements that are unique to either a or b,
but not in both.

4. a.isdisjoint(b): Returns True if sets a and b have no elements in common,


otherwise `ndling collections of unique elements.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Adding elements
set1.add(5) # After adding 5 to set1: {1, 2, 3, 4, 5}
set1.update([6, 7]) # After updating set1 with [6, 7]: {1, 2, 3, 4, 5,
6, 7}

# Removing elements
set1.remove(2) # After removing 2 from set1: {1, 3, 4, 5, 6, 7}
set1.discard(10) # No error even if 10 is not in set1: {1, 3, 4, 5,
6, 7}

# Set operations
union_set = set1.union(set2) # Union of set1 and set2:
{1, 3, 4, 5, 6, 7}
intersection_set = set1.intersection(set2) # Intersection of set1 and
set2: {3, 4}
difference_set = set1.difference(set2) # Set difference (set1 -
set2): {1, 6, 7}
symmetric_difference_set = set1.symmetric_difference(set2) #
Symmetric difference of set1 and set2: {1, 5, 6, 7} # A Δ B = (A ∪ B)
- (A ∩ B)

# The symmetric difference of two sets contains elements that are


unique to either set, excluding the elements that are common to both
sets

print(set1) # Output: {1, 3, 4, 5, 6, 7}


print(union_set) # Output: {1, 3, 4, 5, 6, 7}
print(intersection_set) # Output: {3, 4}
print(difference_set) # Output: {1, 6, 7}
print(symmetric_difference_set) # Output: {1, 5, 6, 7}

{1, 3, 4, 5, 6, 7}
{1, 3, 4, 5, 6, 7}
{3, 4, 5, 6}
{1, 7}
{1, 7}

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Intersection update
# Updates set1 with the intersection of set1 and set2,
# keeping only the elements that are common to both sets.
set1.intersection_update(set2)
print(set1) # Output: {3, 4}

# Difference update
# Updates set2 by removing the elements present in set1 from set2.
set1 = {1, 2, 3, 4}
set2.difference_update(set1)
print(set2) # Output: {5, 6}

# Symmetric difference update


# Updates set2 with the symmetric difference of set1 and set2,
# keeping only the elements that are unique to either set1 or set2,
but not in both.
set1 = {1, 2, 3, 4}
set2.symmetric_difference_update(set1)
print(set2) # Output: {1, 2, 5, 6}

# Is disjoint
# Checks if set1 and set2 have no elements in common.
set1 = {1, 2, 3, 4}
set2 = {5, 6, 7}
is_disjoint = set1.isdisjoint(set2)
print(is_disjoint) # Output: True (set1 and set2 have no elements in
common)

{3, 4}
{5, 6}
{1, 2, 3, 4, 5, 6}
True

a={"Apples","Bananas","Oranges"}
b={"Bananas","Oranges","Pine Apples","Dragon Fruits"}
print("Before:")
print(a)
print(b)
b.update(a)
print("After:")
print(a)
print(b)

Before:
{'Bananas', 'Oranges', 'Apples'}
{'Bananas', 'Oranges', 'Pine Apples', 'Dragon Fruits'}
After:
{'Bananas', 'Oranges', 'Apples'}
{'Oranges', 'Apples', 'Pine Apples', 'Bananas', 'Dragon Fruits'}

a.discard('rrr') #no error if key not there

a.pop() #randomly deletes a value

'Bananas'

• issubset(other_set): Returns True if the set is a subset of the specified set,


otherwise False.
• issuperset(other_set): Returns True if the set is a superset of the specified set,
otherwise False.

• set.isdisjoint(other_set): , Returns True if there are no common elements


between the two sets otherwise, otherwise False.

a={1,2,3,4}
b={3,4}
b.issubset(a)

True

a.issuperset(b)

True
print(a)
print(b)
a.isdisjoint(b)

{1, 2, 3, 4}
{3, 4}

False

## Problems

# sum of all Unique Numbers in List


l=[1,2,3,5,6,5,6,8,2]

s=set()

for i in l:
s.add(i)

sum_of_uniques=0

for i in s:
sum_of_uniques+=i
print(sum_of_uniques)

25

# Make Unique Array


# Find no of elements to be removed to make an array of all distinct
elements

# using sets
l=[1,2,3,4,5,1,2,3,4]
s= set()

elements=0

for i in l:
if i in s:
elements+=1
else:
s.add(i)

print(elements)

# Make Unique Array


# Find no of elements to be removed to make an array of all distinct
elements
# using dictinary
l=[1,2,3,4,5,1,2,3,4]
d={}

elements=0

for i in l:
if d.get(i,0)!=0:
elements+=1
else:
d[i]= d.get(i,0)+1

print(elements)

# Highest Frequency number

test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4,9,9]

print ("Original list : " + str(test_list))

# using naive method to


# get most frequent element
max = 0
res = test_list[0]
for i in test_list:
freq = test_list.count(i)
if freq > max:
max = freq
res = i

# printing result
print ("Most frequent number is : " + str(res)) #if two same freq,
first value return

Original list : [9, 4, 5, 4, 4, 5, 9, 5, 4, 9, 9]


Most frequent number is : 9

# using dictionary
test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4,9,9]
test_list = test_list[::-1]

dict ={}
for i in test_list:
dict[i]=dict.get(i,0)+1
max_freq=0

for i in dict:
if dict[i]>max_freq:
max_freq= dict[i]
max_freq #if two same freq, last stating value return

# ********* **************** ***********


# Given an array that might contain duplicate elements, find the
maximum possible distance between occurrences of two repeating
elements
# i.e. elements having same value. If there are no duplicate elements
in the array, return 0.

arr = [1, 3, 1, 4, 5, 6, 4, 8]
max_distance=0
for i in range(0,len(arr)):
val =arr[i]
for j in range(i+1,len(arr)):
if arr[j]==val:
dist=j-i
if max_distance<dist:
max_distance= dist

print(max_distance)

# First non repeating character


str="aDcadhc"
non_repeating=str[0]
for i in range(0,len(str)):
val= str[i]
if (val in str[i+1:])==False:
non_repeating=val
break
print(non_repeating)

str="abc def"
'd' in str[5:]

False

# Different Names
# print repeating names in a str

str="Abhishek harshit Ayush harshit Ayush Iti Deepak Ayush Iti"


dic={}
for i in str.split():
dic[i]=dic.get(i,0)+1
repeat_exist=False
for i in dic:
if dic[i]>1:
repeat_exist=True
print(i," ",dic[i])

if repeat_exist == False:
print(-1)

harshit 2
Ayush 3
Iti 2

# print even time repeated value, if two or more print first

arr=[2, 3, 4, 4, 4, 4, 5, 3, 5]
dic={}
for i in arr:
dic[i]=dic.get(i,0)+1

for i in dic:
if dic[i]%2==0:
print(i)
break
else:
print(-1)

#***********
# Unique triangles
# A triangle is said to be unique if there is no other triangle with
same set of sides.

# sample input
# 5
# 7 6 5
# 5 7 6
# 8 2 9
# 2 3 4
# 2 4 3

n = int(input())

arr = [list(map(int, input().split())) for x in range(n)]


arr
5
1 2 3
4 5 6
7 8 9
7 8 9
1 2 3

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [7, 8, 9], [1, 2, 3]]

#*****************
# Pairs with difference K

l=[5,1,9,8,12]
k=4

pairs_nums=0
for i in range(0,len(l)-1):
for j in range(i+1,len(l)):
if abs(l[i]-l[j]) ==k:
print(l[i]," ",l[j])
pairs_nums+=1

print(pairs_nums)

5 1
5 9
8 12
3

You might also like