0% found this document useful (0 votes)
8 views44 pages

Python Notes by Payal

Python is a high-level, object-oriented programming language known for its simplicity and versatility, founded by Guido van Rossum. It is widely used in various fields such as data science, web development, and machine learning, and supports features like dynamic memory allocation and a rich standard library. The document also covers Python variables, data types, operators, and comments, providing examples and explanations for each concept.

Uploaded by

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

Python Notes by Payal

Python is a high-level, object-oriented programming language known for its simplicity and versatility, founded by Guido van Rossum. It is widely used in various fields such as data science, web development, and machine learning, and supports features like dynamic memory allocation and a rich standard library. The document also covers Python variables, data types, operators, and comments, providing examples and explanations for each concept.

Uploaded by

neelam1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Python Language?

Ans. Python is a simple general purpose, high level and object oriented programming language.
Python is an interpreted scripting language. Guido van Rossum is known as founder of Python
programming.

Features:-

 Easy to use and learn.


 Expressive language.
 Interpreted language.
 Object-Oriented language.
 Open source language.
 Learn standard library.
 GUI Programming support.
 Dynamic Memory Allocation.

Where is Python Used:-


In almost every technical field . Python is very useful language.
 Data science.
 Data mining.
 Mobile Application.
 Software development.
 Web Application.
 Software Development.
 Enterprise Application.
 Machine learning.

Python Variables:-
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value. Variable names can be a group of both letters and digits, but they
have to begin with a letter or an underscore.

Identifier Naming:-
Variable are the example of identifier. An identifier is used to identify the literals and used in the
program.
1. The first character of the variable must be an alphabet or underscore (_).
2. All the character except the first character may be an alphabet of lower-case (a-z), upper-
case (A-Z) underscore or digits (0-9).
3. Identifier name must not contain any white space, or special character (!,@,#,%,^,&,*).
4. Identifier name must be similar to any keyboard define in the language.
5. Example of valid identifier: a123,_n,n_9 etc.
6. Example of invalid identifier: 1a,n%4,n 9 etc.

Object Reference:-
It is necessary to understand now the Python interpreter works when we declare a variable. The
process of treating variable is somewhat different from many other programming language.
Python is the highly object-oriented programming language.
Example:-
print(“payal”)

Output- payal

Example:-
Print(type(“payal”))

Output- <class ‘str’>

Object Identity:-
Id() function
Example:

a=50
b=a
print(id(a))
print(id(b))
Output-
140734982691168
140734982691168

Variable names:-
We have already discussed how to declare the valid variable. Variable names can
be any length can have uppercase(A to Z), lowercase(a to z), the digit (0-9) and underscore character
(_).

Example:-
name=”payal yadav”
age=20
marks=90
print(name)
print(age)
print(marks)
Output:-
payal yadav
20
90
Consider the following valid variables name:-
name=”A”
Name=”B”
naMe=”C”
NAME=”D”
n_a_m_e=”E”
_name=”F”
name_=”G”
na56me=”I”
print(name,Name,naMe,NAME,n_a_m_e,_name,name_,na56me)
Output:- A B C D E F G H I

Python Data Type:-

Example:-
a=10
b=”Hi payal”
c=80.6
print(type(a))
print(type(b))
print(type(c))
Output:-
<type ‘int’>
<type ‘str’>
<type ‘float’>

Standard data type:-


A variable can hold different types of value for example: a person name must be
stored as a string whereas its id must be stored as an integer.
1. Number
2. Sequence type
3. Boolean
4. Set
5. Dictionary

Numbers:-
a=5
print(“the type of a”, type(a))
b=40.5
print(“the type of b”,type(b))
c=1+3j
print(“the type of c”, type(c))
print(“c is complex number”, is instance (1+3j, complex))

Output:-

The type of a <class ‘int’>


The type of b <class ‘float’>
The type of c <class ‘complex’>
C is complex number: True

Keyword:-
Python keyword are special reserved words that convey a special meaning to the
compiler/ Interpreter.
Python keywords:-

True assert else global raise


False def finally for try
None class elif if or
and continue del from return
as break expect import pass
nonlocal in not is lambda

and:-
it is a logical operator. It is used to check the multiple condition.

A B Y=A and B
false false false
false true false
true false false
true true true

Or:-
It is a logical operator in python. It return true if one of the condition is true.

A B Y =A or B
false false false
false true true
true false true
true true true

not:-
It is a logical operator and inverts the truth value.

A =Ā
false true
true false

Python Literals:-
Python literals can be defined as data that is given in a variable or constant.
1. String literals:-
String is enclosed a text in the quotes. we can use both single as well as double quotes
to create a string.
Type of string:-
There are two types of string support in python.
a) Single-line string:-
String that are terminated with in a single line are known as single line string.
Example:-
Text 1= ‘payal’
b) Multi-line string:-
A piece of a text that is written in multiple line is known as multiple line string.
There are two way to create multiple string.
(i) (\) slash
Example:-
text1= ‘hello \
khushi’
print(text1)
Output:-
‘hello khushi’

(ii) using triple quotes marks:-


Example:
str2=’’’welcome
to
zedking’’’
print(str2)
Output:
welcome
To
zedking

2. Numeric Literals:-
Numeric Literals are immutable. Numeric literals can belong to following
four different numerical type.
(i)Integer (ii) float (iii) complex (iv) long integer

Example:-
x=ob1000 # Binary
y=100 # Decimal
z=oq215 #Octal
u=ox12d #Hexadecimal

# float Literal
float_1=100.5
float_2=1.5c2

#complex literal
a=5+3.14j
print(x,y,z,u)
print(float_1,float_2)
print(a,[Link],[Link])

output:-
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0

3. Boolean Literals:-
A boolean literal can have any of the two values. True or False.
Example:
x=(1==True)
y=(2==False)
z=(3==True)
a=True+10
b=False+10
print(“x is=”, x)
print(“y is=”, y)
print(“z is=”, z)
print(“a is=”, a)
print(“b is=”, b)

Output:-

x is True
y is False
z is False
a is 11
b is 10

4. Special Literals:-
Python contains one special literal i.e. None.
Example-
val1=10
val2=None
print(val1)
print(val2)

Output:-
10
None

5. Literal collection:-
Python provides four types of literal collection such as list literals,
Tuple literals, disc literals, set literals.
(a)list:-
 List contain item of different data types. List are mutable i.e.
modifiable.
 The values stored in list are separated by comma(,) and enclosed with
in square bracket([]). We can store different type of data in a list.
Example-
list=[‘payal’, 2005, 20.3,’yadav’]
list1=[2003,’sharma’]
print(list)
print(list+list1)

Output-

[‘payal’,2005,20.3,’yadav’]
[‘payal’,2005,20.3,’yadav’,2003,’sharma

(b) Dictionary:-
 Python dictionary stores the data in the key- value pair.
 It is enclosed by curly-braces {} and each pair is separated by
the comman(,).
Example-
dict={‘name’:’ravi’,’age’:24,’roll_no’:101}
print(dict)

Output-
{name:’ravi’,’age’:24,’roll_no’:101}
(c) Tuple:-
 Python is a collection of different data type.
 It is a immutable which means it cannot be modified after creation
 It is enclosed by the parenthesis and each element is separated by
comma(,).
Example-
tup=(10,20,”rohit”,[2,3,4])
print(tup)
Output-
(10,20,’rohit’,[2,3,4])

(d)Set:-
 Python set is collection of the unordered data set.
 It is enclosed by the {} and each element is seprated by the comma(,).
Example-
Set={‘apple’,’grapes’,’guava’,’papaya’}
print(set)
Output-
{‘guava’,’apple’,’papaya’,’grapes’}

OPERATORS
The operator can be defined as a symbol which is responsible for a particular operation b/w two
operands. Operator are the pillars of a program on which the logic is built in a specific programming
language.
 Arithmetic operator
 Comparison operator
 Assignment operator
 Logical operator
 Bitwise operator
 Membership operator
 Identity operator

Arithmetic operator:-
Arithmetic operator are used to perform arithmetic operation between two
operands. It included +(addition), -(subtraction), *(multiplication), /(divide),% (remainder),
//(forward) and **(exponent) operator.

Operator Description
+ It is used to add two operands. For example if a=20, b=10 a+b=30
- It is used to subtraction the second operand from the first operand .
if the first operand is less than the second operand , the value result
negative for example- if a=20, b=10 then a-b=10
/ It return the quotient after dividing the first operand by the second
operand . for example a=20, b=10 then a/b=10
* It is used to multiply one operand with the other . for example if
a=20, b=10 then a*b=200
% It return the remainder after dividing the first operand by the
second operand . for example if a=20, b=10 then a%b=0
** It is an exponent operator represented as it calculates the first
operand power to second operand
// It given the float value of the quotient produced by dividing the two
operand.

Comparison operator:-
Comparison operator are used to compare the value of the two
operands and returns Boolean true or false accordingly. The comparison operator are
described in the following table.

operator Description
== If the value of two operands is equal then the condition become
true.
!= If the value of the operands is not equal then the condition
become true.
<= If the first operands is less than or equal to the second operand,
then the condition become true.
>= If the first operands is greater than or equal to the second
operand, then the condition become true.
> If the first operands is greater than the second operand, then
the condition become true.
< If the first operands is less than the second operand, then the
condition become true.

Assignment operator:-
The assignment operator are used to assign the value of the right
expression the left operand. The assignment operator are described in the following table.

operator Description
= It assigns the value of the right expression to left operand.
+= It increases the value of the left operand by the value of the right
operand and assigned the modified value back to left operand. For
example if a=10 and b=20 then a+=b and therefor a=30
*-= It decreases----- a=20, b=10 then a-=b, a=10
*= It multiplies ------a=10, b=20 then a*=b, a=200
%= It devide the value of the left operand by the value of high operand and
assign the remainder back to the left operand .
For example a=20, b=10 then a%=b , a=0
**= a**b= will be equal to a=a//b , for example if a=4 ,b=2, a**=b will assign
4**2=16 to a
//= a//=b will be equal to a=a//b for example if a=4,b=3, a//=b will assign
4//3=1 to a

Bitwise operator:-
The bitwise operator perform bit by bit operation on the value of the two
operands.

Example-
if a=7
b=6
then, binary(a)=0111
binary(b)=0110
hence, a&b=0011
a|b =0111
a^b =0100
~a=1000

operator Description
&(binary and) If both the bit at the same place in two operand are 1
then 1 is copied to the result otherwise 0 is copied
|(binary or) The resulting bit will be 0 if the both bits are zero
otherwise the resulting bit will 1.
^ (binary xor) The resulting bit will be one(1) if both the bits are
different; otherwise the resulting bit will be 0.
~(negation) The left operand value is moved left by the number of
bits present in the right operand.
<<(left shift) The left shift operand value is moved left by the number
of bits present of bits present in the right operand.

Logical operator:-
The logical operator are used primary in the expression evaluation to
make a decision. Python support the following logical operators.

operator Description
and If both the expression are true, then the condition will
be true, if a and b are the two expression, a=true and
b=true therefor a and b=true
or If one of the expression is true, then the condition will
be true, if a and b are the two expression a=true and
b=false then a or b=true
Not If an expression a is true, then not (a) will be false and
vice-verse.

Membership operator:-
Python membership operator are used to check the membership of
value inside a python data structure. If the value of is present in the data structure, then the
resulting value is true otherwise its return false.

operator Description
in It is evaluated to be true if the first operand is found in the
second operand (list, tuple or dictionary)
not in It is evaluated to be true if not found in the second operand
(list, tuple dictionary)

Python Comment:-

1. Single line comment(#)


2. Multiline comment(‘’’--------‘’’)

Example-
Comperision operator
a=10
b=20
print(‘a<b:’, a<b) Output:-
a<b :true
a>b: false
a<=b :true
a>=b :false
a==b :false
a!=b :true

print(‘a>b:’, a>b)
print(‘a<=b:’, a<=b)
print(‘a>=b:’, a>=b)
print(‘a==b:’,a==b)
print(‘a!=b:’,a!=b)

Example- Logical Operator

a) And(&)

True & True


True& False
False & True
False & False

Output-
True
False
False
False

b) Or(|)

True | True
True |False
False| True
False| False

Output-
True
True
True
False

c) Not

not True
not False
not 15>13
not((15>13)and(15>2))
not(15>13 and 15<33)
not(15<13 and 15<33)

output-
False
True
False
False
False
True

AND operator:- execution-


Example- 10=1010
bin(10) 3=0011
bin(3) 10&3 1010
10 & 3 &
0011
Output- 0010
‘0b1010’
‘0b11’
2

OR operator:- execution-
Example- 10=1010
bin(10) 3=0011
bin(3) 10&3 1010
10 &|3 |
0011
Output- 11 decimal
‘0b1010’
‘0b11’
11

XOR operator:- execution-


Example- 10=1010
bin(10) 3=0011
bin(3) 10^3 1010
10 ^ 3 ^
0011
Output- 9 decimal
‘0b1010’
‘0b11’
9
Left shift operator:- execution-
Example- 10=1010
bin(10) 10<<3 1010<<3
bin(3)
10 << 3 1010000
80 decimal
Output-
‘0b1010’
80

Right shift operator:- execution-


Example- 10=1010
bin(10) 3=0011
10<<3 1010<<3
bin(3)
10 << 3 1 decimal

Output-
‘0b1010’
1

Conditional Statement

In python conditional statement perform different actions depending on whether a


specific Boolean constraint evaluates a true or false.
 If<test-expression>:
Statement(s)

Example-
x=100
y=200
if(x>y):
print(“x is less than y”)

Output-
x is less then y
 Example-
X=int(input(“enter value of n”))
If(x>0):
Print(“number is positive”)
elif(x<0)
print(“number is negative”)

Output:-
enter value of n:5
number is positive

 Example-
Find biggest value of given 2 number from the command line.

a=int(input(“enter value of a:”))


b=int(input(“enter value of b:”))
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

output-
enter value of a: 10
enter value of b:8
a is greater
 Example-
Find biggest value of given 3 numbers from the command line.

a=int(input(“enter value of a:”))


b=int(input(“enter value of b:”))
c=int(input(“enter the value of c:”))
if a>b & a>c:
print(“a is greater”)
elif b>a & b>c:
print(“b is greater”)
else:
print(“c is greater”)

output-
enter value of a: 10
enter value of b:20
enter value of c:15
b is greater

 Example-
Find your grade, above 90-grade A+, above 80-grade A, above 70- grade b,
above 60-grade c, otherwise fail.

Grade=int(input(“enter marks:”))
if grade>90:
print(“A+”)
elif grade>80:
print(“A”)
elif grade>70:
print(“b”)
elif grade>60:
print(“c”)
else:
print(“fail”)

output-
enter marks:90
A

 Example-
Find given year is leap year or not.

year=int(input(“enter year:”))
if year%400==0:
print(“leap year”)
elif year%100==0:
print(“not leap year”)
elif year%4==0:
print(“year is leap year”)
else:
print(“not leap year”)

output-
enter year:2005
not leap year

LOOP
The flow of program written in any programming language is sequential by default.
Sometimes we may need to alter the program. The execution of a specific code may need to
be executed repeated several number of times.
Types of loops-
While loop:-
Syntax
While expression:
statement
 Example-
Print 1 to 5 natural number.
i=1
while i<=5:
print(i)
i=i+1

Output-

1
2
3
4
5

 Example
Print write a program to find sum of 10 natural number.

i=1
sum=0
while i<=10:
sum=sum+i
i=i+1
print(sum)

output-

55

 Example
write a program to find sum of even number between 1 to 10 natural
number.

i=1
sum=0
while i<=10:
if(i%2==0)
sum=sum+i
i=i+1
print(sum)
output-

30

 Example-
Program to print table of given numbers.

n=int(input(“enter value of n:”))


i=1
while i<=10;
print(n,”*”,i,”=”,n*i)
i=i+1

output-

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

 Break statement:-

i=1
while i<=5:
print(i)
i=i+1
if(i==3):
break
else:
print(“the while loop executed”)

output-

1
2
 Continue statement:-
i=0
while i<=10:
i=i+1
if i==5:
continue
print(i)

PATTERN

* i=1
** while i<=5:
*** print(“*”*i)
**** i=i+1
*****

******
***** i=6
**** while i>=1:
*** print(“*”*i)
** i=i-1
*

Write a program check weather number is palindrome or not.


Ans:-
n=int(input(“enter number”))
num=n
rev=0
while n>0:
rem=n%10
rev=rec*10+rem
n=n//10
if rev==num:
print(“number is palindrome”)
else:
print(“number is not palindrome”)
output-
enter number: 121
number is palindrome

Write a program check weather number is Armstrong or not.


Ans:-
n=int(input(“enter number”))
num=n
sum=0
while n>0:
rem=n%10
sum=sum+(rem*rem*rem)
n=n//10
if sum==num:
print(“number is armstrong”)
else:
print(“number is not armstrong”)
output-
enter number: 153
number is armstrong
for loop:-
syntax:-
for iterator var in sequence:
body statement(s)

 Example:-

str=”payal”

for x in str:

print(x)

output-

p
a
y
a
l

 Example-
print(“using two argument in range()”)
for i in range(10,20):
print(i, end=’,’)

output-
using two argument in range()
10,11,12,13,14,15,16,17,18,19
 Print odd number between 1-100 natural number.

print(“odd number between 1 and 100”)


for i in range(1,100,2):
print(i,end=’,’)

output-

odd number between 1 and 100


1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,
37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,
69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99

Write a program to display * below form.

* n=int(input(“enter number:”))
*** for i in range(1,n+1):
**** for j in range(1,i+1):
***** print(“*”,end=” ”)
print()

write a program to display * in pyramid style

n=int(input(“enter number of row”))


for i in range (1,n+1):
print(“ ”* (n-i), end=” “)
print(“*”*i)

write a program to display * below form

n=int(input(“enter no of rows:”)) *
for i in range(1,n+1): **
print(“ ”*(n-i),end=” “) ***
print(“*” *i) *****
******

Write a program to display * in ‘N’ style.

for row in range(6): * *

for(col in range(6): * * *

if col==0 or col==5 or (row== col and col>0 and col<5) * * *

print(“*”,end=” “) * *

else:

print(end=” ”)

print()

Write a program to display numbering pattern .

1 for i in range(1,6):
12 for j in range(1+i+1):
123 print(j, end=” “)
1234 print();
12345

Write a program to display numbering pattern.

1
22 for i in range(1,6):
333 for j in range(1,i+1):
4444 print(i, end=” “)
55555 print();
Write a program to display * pattern.

***** for i in range(5,0-1):


**** for j in range(1,i+1):
*** print(“*”, end=” “)
** print();
*

Write a program to display numbering pattern.

55555 for i in range(5,0-1):


4444 for j in range(1,i+1):
333 print(i, end=””)
22 print();
1

Write a program to display * pattern.

* for i in range(1,6):
** for j in range(1,i+1):
*** print(“*”, end=” “)
**** print()
***** for i in range(4,0,-1):
**** for j in range(1,i+1):
*** print(“*”, end=” “)
** print()
*

Write a program to display numbering pattern.

54321 for i in range(5,0,-1)


4321 for j in range(i,0-1)
321 print(x, end=” ”)
21 print()
1
Write a program to display numbering pattern.

1 x=1
23 for i in range(1,5):
456 for j in range(1,i+1):
78910 print(x, end=” “)
x=x+1
print()

Break Statement:-
Wap to use of break statement inside for loop.

for i in range(10):

print(“i value:”,i)

if(i==4)

break

print(“after for loop”)

output-

i value: 0

i value: 1

i value:2

i value:3

i value :4

After for loop

Pass statement:-
for a in ‘python’:

if a==’h’

pass

print(“this is pass block”)

print(“current letter:”,a)

print(“good bye!)

output-

current letter:p
current letter:y

current letter:t

this is pass block

current letter:h

current letter:o

current letter:n

good bye!

Example of for loop:

 Print display hello message n times.

n=int(input(“enter value of n:”))

for i in range(1,n):

print(“hello”)

 Print counting 1-n times

n=int(input(“enter value of n:”))


for i in range(1,n+1):
print(i)
 Table of numbers
n=int(input(“enter value of n:”))
for i in range(1,11):
print(n*i)
print(n,”*”,I,”=”,n*i)

 Print factorial of n numbers

n=int(input(“enter value of n:”))

f=1

for i in range(n,0,-1):

f=f*i

print(“factorial of”,n,”is=”,f)

 Print display all even number between 1-n

n=int(input(“enter value of n:”))


for i in range(1,n+1):
if (i%2==0):
print(i)
 Sum & avg of n natural number

n=int(input(“enter value of n:”))


sum=0
for i in range(1,n+1):
sum=sum+i
print(“sum is”,sum)
avg=sum/n
print(“avg is”, avg)

while loop

 Example of while loop


 Print display payal message n times.

n=int(input(“enter value of n:”))

i=1

while i<=n:

print(“payal”)

i=i+1

 Print display counting 1-n times.

n=int(input(“enter value of n:”))


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

 Print display counting n-1 times.

n=int(input(“enter value of n:”))


i=n
while i>=1:
print(i)
i=i-1

 Write a program to print factorial of n number.

n=int(input(“enter value of n:”))


f=1
while i>=1:
f=f*i
i=i+1
print(“factorial is”,n,”is=”,f)

 Write a program to print all even number between 1 to 100.

i=1
while i<=100:
if i%2==0:
print(i)
i=i+1
 Write a program to find sum & avg of n number.

n=int(input(“enter value of n:”))


sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print(“sum is”, sum)
avg=sum/n
print(“avg is=”, avg)
 Write a program to find swapping of 2 number with using third variable.

a=int(input(“enter value of a:”))


b=int(input(“enter value of b:”))
print(“before swapping”)
print(“value of a=”,a )
print(“value of b=”,b)
c=a
a=b
b=c
print(“after swapping”)
print(“value of a=”,a )
print(“value of b=”,b)

 Write a program to find swapping of 2 number without using third variable.


a=int(input(“enter value of a:”))
b=int(input(“enter value of b:”))
print(“before swapping”)
print(“value of a=”,a )
print(“value of b=”,b)
a=a+b
b=a-b
a=a-b
print(“after swapping”)
print(“value of a=”,a )
print(“value of b=”,b)

 Write a program to print student profile in python.


Name _____
Class _____
Roll no ____
-------Result-------
Eng _____
hindi _____
physics _____
chemistry_____
maths ____
total
percentage
Grade

Ans- print(“------------student profile-------“)


a=input(“name:”)
b=input(“class:”)
c=int(input(“roll no:”))
print(“--------Result----------“)
d=int(input(“Eng:”))
e=int(input(“hindi:”))
f=int(input(“physics:”))
g=int(input(“chemistry”))
h=int(input(“maths:”))
print(“total:”)
print(d+e+f+g+h)
per=(d+e+f+g+h)
print(per)
i=input(“Grade:”)
if per>90:
print(“A+”)
elif per>80 and per<=90:
print(“B”)

else:

print(“C”)

Sequence Data Type

List is order collection in python. If we want to represent a group of individual object as a single
entity where insertion order preserved and duplicates are allowed then we should go for list.

Creation of the list object:-

1) Create empty list object as follows.


list=[]
print(list)
print(type(list))

Output-

[]
<class ‘list’>

2) Create list with elements

list1=[10,20,30,40]
list2=[‘a’,’b’,’c’,’d’]
list3=[True, False]
print(list1)
print(list2)
print(list3)

3) Create list with dynamic inputs.

list=eval(input(“enter list:”))
print(list)

Output-

enter list: [10,20,30]


[10,20,30]

4) Create a list with the use of string.

list=[‘you create your own reality ’]


print(“\n list with the use of string: “)
print(list)

Output-

list with the use of string:


[‘you create your own reality

5) Create a list with use of multiple value.

list=[“apple”,”banana”,”pine”]
print(list)
Output-

[‘apple’,’banana’,’pine’]

6) Create a list having duplicate values.

list=[1,2,4,4,3,3,3,6,5]
print(list)

Output-

[1,2,4,4,3,3,3,6,5]
7) Creating a list with mix type of values.

list=[101,’payal’,5.6,True,(1+2j)]
print(list)

Output-

[101,’payal’,5.6,True,(1+2j)]

 Create a list with list () function.


Example-

#empty list
Print(list())
#vowel string
s= ’Be a master’
print(s)
#vowel list
Vowel list=[‘a’,’e’,’I’,’o’,’u’]
Print(list(vowel list))

Output-

[]
[‘B’,’e’,’ ’,’a’,’ ‘,’m’,’a’,’s’,’t’,’e’,’r’]
[‘a’,’e’,’i’,’o’,’u’]

 Create list with split() function


Example-

x=’one, two, three’


y=[Link](‘ , ‘)
print(y)

Output-

[‘one’,’two’,’three’]
a,b,c= [Link](‘,’)
a
‘one’
b
‘two’
c
‘three’
 Accessing element from the list:-

Python support both positive and negative index

121 111 127 98 95 67

 Example 1:
Accessing of element from using positive index.

list=[“apple”,”banana”,”mango”]
print(list)
print(“accessing a element from the list”)
print(“1st [0]:” , list[0])
print(“1st [1]:” ,list[1])
print(“1st [2]:” ,list[2])

Output-

[‘apple’,’banana’,’mango’]
Accessing a element from the list
1st [0]: apple
1st [1]:banana
1st [2]:mango

 Example 2:
Accessing of element from using negative index.

a=[“apple”,”banana”,”mango”]
print(a)
print(“a[-1]:” , a[-1])
print(“a[-2]:” ,a[-2])
print(“a[-3]:” ,a[-3])

Output-

[‘apple’,’banana’,’mango’]
a[-1]:mango
a[-2]:banana
a[-3]:apple

 Example 3:
Accessing of element from list using looping.

a=[“apple”,”banana”,”mango”]
print(a)
for i in range(0,len(a)):
print(i,”:”, a[i])

Output-

[‘apple’,’banana’,’mango’]
0:mango
1:banana
2:apple
 Example 4:
Accessing of element from a multi-dimensional list.

a=[ [1,2], [‘mango’,’banana’]]


print(“Accessing of element from a multi-dimensional list)
print(‘a[0][0]:’ , a[0][0])
print(‘a[0][1]:’ ,a[0][1])
print(‘a[1][0]:’ ,a[1][0])
print(‘a[1][1]:’ ,a[1][1])

Output-

Accessing of element from a multi-


dimensional list
a[0][0]:1
a[0][1]:2
a[1][0]:mango
a[1][1]:banana

 Example 5:
Addition of elements in a list.

a=[ ]
print(“blank list:”)
print(a)
[Link] (10)
[Link] (20)
[Link] (30)
print (“after addition of three elements:”)
print (a)

Output-

blank list:
[]
after addition of three elements:
[10.20,30]

 Example 6:
Addition of elements from 10-19 in list.
a=[ ]
for i in range (10,20):

[Link](i)

print(“after addition of elements from 10-19:”)

print(a)

Output-

after addition of elements from 10-19:


[10,11,12,13,14,15,16,17,18,19]

 Example 7:
Adding element to the list to a list.

a=[ ]

for i in range (1,4):

[Link](i)

print(“\n list after addition of elements 1-3:”)

print(a)

b=[‘apple’,’boy’]

[Link](a)

print(“list after addition of list:”)

print(b)

Output-

list after addition of elements 1-3:


[1,2,3]
List after addition of list:
[‘apple’,’boy’,[1,2,3]]

 Example 8:
Using insert, addition of element specific position.
a=[100,200,300]
[Link](1,400)
print(a)
[Link](2,”your name”)

Output-

[100,200,300]
[100,400,’your name’,200,300]

 Example 9:
Addition of multiple elements using extend methods.

a=[1,2,3,4,5]
[Link]([6,7,8])
print(a)

Output-

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

 Example 10:
Removing element from a list . (Remove())

a=[10,20,30,40]
print(a)
[Link](30)
print(a)

Output-

[10,20,30,40]
[10,20,40]

 Example 11:
If the specified element not present in list we will get an error message.

a=[10,20,30,40]
print(a)
[Link](40)
print(a)

Output-

[10,20,30,40]
[10,20,30]

 Example 12:
Write a program to remove element in python.

a=[10,20,30]
print(a)
[Link]()
print(a)
[Link]()
print(a)
[Link]()
print(a)

Output-
[10,20,30]
[10,20]
[10]
[]

 Example 13:
Order list element of list:- (reverse())
a=[10,20,30,40]
print(“before reversing list items”)
print(a)
[Link]()
print(“after reversing list item”)
print(a)

Output-

before reversing list item


[10,20,30,40]
after reversing list item
[40,50,60]

 Example 14:

a=[‘a’,’b’,’c’,’d’]
print(“before reversing list items”)
print(a)
[Link] ()
print(“after reversing list items”)
print(a)

Output-

before reversing list items


[‘a’,’b’,’c’,’d’]
after reversing list items
[‘d’,’c’,’b’,’a’]

 Example 15:

Accessing individual element in reverse order.

Syntax-

str=’payal’

print(list(reversed(str)))

print(‘p’,’a’,’l’,’u’)

print(list (reversed (type)))

rng=range(1,5)

print(list(reversed(rng)))

list=[1,2,4,3,5]

print(list(reversed(list)))

Output-
[‘l’,’a’,’y’,’a’,’p’]
[‘u’,’l’,’a’,’p’]
[4,3,2,1]
[5,3,4,2,1]

sort():
syntax:- [Link](key=…,reverse=…)

 Example 16:

x=[2,5,3,90,12]

[Link]()

print(x)

Output-

[2,3,5,12,90]

 Example 17:
Reverse using sort()

num=[70,50,60,1,20]
[Link](reverse=True)
print(num)

Output-

[70,60,50,20,1]

 Example 18:
Concatenation (+)

x=[10,20,30]
y=[40,50,60]
z=x+y
print(z)

Output-

[10,20,30,40,50,60]

 Example 19:
Repetition operator (*)

x=[10,20,30]
z=x*3
print(z)

Output-

[10,20,30,10,20,30,10,20,30]

Tuple
Tuple is a collection of python objects separated by commas. Tuple is exactly same as list expect that
is immutable.

Properties:-

 Insertion order is preserved.


 Duplicate are allowed
 Heterogeneous objects are allowed
 Tuple support both +ve and –ve index.

Example-

I. Create a tuple

thistuple=(“dca”,”dca”,”dcaa”,”pgdca”)
print(“thislist) Note:- Allow Duplication

Output-

(‘dca’,’dca’,’dcaa’,’pgdca’

II. Tuple length-

thistuple=(“apple”,”banana”,”mango”)
print(len(thistuple)

Output-

III. Access tuple items-

thistuple=(‘apple’,’banana’,’charry’)
print(thistuple[1])

Output-

banana
IV. Negative Index-
thistuple=(‘apple’,’banana’,’charry’)
print(thistuple[-1])

Output-

Cherry

V. Range of index-

thistuple=(“apple”,”banana”,”orange”,”cherry”,”kiwi”)
print(thistuple(2:5)

Output-

(‘orange’,’cherry’,’kiwi’)

VI. Update tuple-


Convert into list to be change it.

x=(“apple”,”banana”,”cherry”)
y=list(x)
y[i]=”kiwi”
x=tuple(y)
print(x)

Output-

‘apple’,’banana’,’cherry’,’kiwi’

VII. Add items:-


Note: you cannot add item to a tuple

VIII. Convert the tuple into a list, add “orange”, and convert other document building blocks.
When you create pictures, charts, or diagrams, they also coordinate back into tuple.

thistuple=(“apple”,”banana”,”cherry”)
y=list(thistuple)
[Link](“orange”)
thistuple=tuple(y)
print(thistuple)

Output-

(‘apple’,’banana’,’cherry’,’orange’)

IX. Remove items-


Note: you can not remove items in a table.
Convert the tuple into a list, remove “apple” and convert it back into a list.
thistuple=(“apple”,”banana”,”cherry”)
y=list(thistuple)
[Link](“apple”)
thistuple=tuple(y)
print(thistuple)

Output-

(‘banana’,’cherry’)

X. Unpack Tuple:-

fruits=(“apple”,”banana”,”cherry”)
a,b,c=fruits
print(a)
print(b)
print(c)

Output-

apple
banana
cherry

XI. Using asterix:-

Assign the rest of the value as a list called red.

fruits=(“apple”,”banana”,”cherry”,”mango”,”strawberry”)
(green,yellow,*red)=fruits
print(green)
print(yellow)
print(red)

Output-

apple
banana
[‘cherry’,’mango’,’strawberry’]

XII. Loop through a tuple:-

thistuple=(“apple”,”banana”,”cherry”)
for x in thistuple:
print(x)

Output-
apple
banana
cherry
XIII. Check length using while loop.

thistuple=(“apple”,”banana”,”cherry”)
i=0
while i<=len(thistyple):
print(thistuple[i])
i=i+1

Output-

apple
banana
cherry

XIV. Join tuple-

tuple1=(“a”,”b”,”c”)
tuple2=(1,2,3)
tuple3=tuple1+tuple2
print(tuple3)

Output-

‘a’,’b’,’c’,1,2,3

XV. Multiply the fruits tuple by 2.

fruits=(“apple”,”banana”,”mango”)
multiply=fruits*2
Print(multiply)

Output-

‘apple’,’banana’,’mango’,’apple’,’banana’,’mango’

SETS
Set is a class treated as data type. A set data type represent unorder collection of elements or to
represent a group of unique value as a single entitiy then we should go for set data type.

Properties:-

 A set doesn’t accept duplicate elements.


 A set is defined by value separated by comma inside braces { }.
 A set data type element can be modified.
 A set doesn’t maintain insertion order.
 A set data type provides dynamic size.
 A set doesn’t allow indexing & slicing.

Example-

 thisset={“apple”,”banana”,”mango”}
print(thisset) note:-refresh page change result

Output-

{‘apple’,’banana’,’mango’}

 Duplicate not Allowed

thisset={“apple”,”banana”,”cherry”,”apple”}
Print(thisset)

Output-

{‘apple’,’cherry’,’banana’}

 Get the length of a set

thisset={“apple”,”banana”,”cherry”}
Print(len(thisset))

Output-

 Set Items ---- data types


 String
 Int
 Boolean
str1={“apple”,”mango”,”banana”}
str2={“1,5,7,9,3}
str3={True,False,True}

output-

{‘apple’,’banana’,’mango’}
{1,3,5,7,9]
{flase,True}
 Tuple()
Syntax: <class ‘set’>

myset={“apple”,”banana”,”mango”}
print(type(myset))
Output-

<class ‘set’>

 The set() constructor:

thisset=set((“apple”,”banana”,”cherry”))
print(thisset)

Output-

{‘cherry’,’apple’,’banana’}

 Access Items:

thisset={“apple”,”banana”,”cherry”}
for x in this set:
print(x)

Output-

Apple
Banana
cherry

 Check if “banana” is present in the set

thisset={“apple”,”banana”,”cherry”}
print(“banana” in thisset)

Output-

True

 Add()-

thisset={“apple”,”banana”,”mango”}
[Link](“orange”)
print(thisset)

Output-

{‘banana’,’apple’,’mango’,’orange’}
 Add set()-

thisset={“apple”,’banana”,”cherry”}
tropical={“pineapple”,”mango”,”papaya”}
[Link](tropical)

Output-

{‘apple’,’cherry’,’pineapple’,’mango’,’papaya’}

 Add elements of a list to a set.

thisset={“apple”,’banana”,”cherry”}
mylist={“kiwi”,”orange”}
[Link](mylist)
print(thisset)

Output-

{‘banana’,’cherry’,’apple’,’orange’,’kiwi’}

 Remove set items:-


Remove () or discard() method.

thisset={“apple”,’banana”,”cherry”}
[Link](“banana”)
print(thisset)

Output-

{‘apple’,’cherry’}

 Join sets:- Using union()

set1={“a”,”b”,”c”}
set2={1,2,3}
set3=[Link](set2)
print(set3)

Output-

{‘b’,2,’a’,1,’c’,3}

You might also like