Monday, 29 July 2024

Python - Unit III

 Python Topics

    1.      List

    2.      Tuples

    3.      Strings

    4.      Dictionaries

    5.      Set


 

1. Python List

Python List

--------------

    ·         Lists are used to store multiple items in a single variable.

    ·         Python list (all items) created inside a square bracket ([])

    ·         List are mutable (can alter List (add, update, delete)

    ·         List items are Empty, ordered, changeable, and allow duplicate values.

 

Python List Syntax:

-----------------------

      list_name = [value1, value2, value3,..., value-n]

 

Example:

----------

->Empty List:

    list=[ ]

->Integer List:

    list=[1,2,3]

->Floating List:

    list=[1.5,2.5,3.6]

->string List:

    list=["hello", "welcome", "python"]

->Mixed List:

    list=[1,2.5,"hello"]

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Accessing Lists

------------------

àList items are indexed, the first item has index [0], the second item has index [1] etc.

-Forward Index: 0, 1, 2, 3, 4...

      -Backward Index: -1,-2,-3,-4...

Ex:

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

 str[0]=10=str[-6],

 str[1]=20=str[-5],

 str[2]=30=str[-4],

 str[3]=40=str[-3],

 str[4]=50=str[-2],

 str[5]=60=str[-1].

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Example Program for Display & Accessing Python List

a = [ ]

b = [10,20,3,5,8,1]

c = [10.5,20.5,3.5]

d = ["welcome", "python"]

e = [12, 5.6, "hello", 25]

print(a)

print(b)

print(c)

print(d)

print(e)

 

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

print(list1)

print (list1 [0])

print (list1 [-1])

print (list1 [1:3])

print (list1 [1:])

print (list1 [:3])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python List Methods

---------------------------

1. append()- Adds an element at the end of the list

2. clear() - Removes all the elements from the list

3. copy()  - Returns a copy of the list

4. count() - Returns the number of elements with the specified value

5. extend()- Add the elements of a list (or any iterable), to the end of the current list

6. index() - Returns the index of the first element with the specified value

7. insert()- Adds an element at the specified position

8. pop()   - Removes the element at the specified position

9. remove()- Removes the first item with the specified value

10.reverse()-Reverses the order of the list

11.sort()  - Sorts the list

12.min(list): Returns the minimum value from the list given.

13.max(list): Returns the largest value from the given list.

14.len(list): Returns number of elements in a list.

15.cmp(list1,list2): Compares the two list.(Not Working 3)

16.list(sequence): Takes sequence types and converts them to lists.

17.del : delete a list

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Example Program for Python Methods

a = [20,30,10,15,10,25]

a1 = ["red", "green", "blue"]

print ("List are", a)

print ("List are", a1)

a.append(5)

print("Append : ",a)

b=a.copy()

print("Copy :",b)

b.clear()

print("clear :",b)

print("10 no of times :",a.count(10))

print("Index :",a1.index("green"))

a1.insert(1,"orange")

print("Insert :",a1)

a1.pop(1)

print("Now List :",a1)

a1.remove("green")

print("Now List :",a1)

a1.reverse()

print("Reverse List :",a1)

a1.sort()

print("Sorting List :",a1)

print("Max :",max(a1))

print("Min :",min(a1))

print("Len :",len(a1))

 

a1=["one","two","three"]

a2=["red","green","blue"]

a1.extend(a2)

del a1

#print(a1) Error

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


 

2. Python Tuple

Python Tuple

-----------------

   §  Tuple is a sequence of immutable objects

   §  Tuple can’t be changed; you cannot change elements of a tuple once it is assigned.

   §  Tuple objects are enclosed within parenthesis and separated by comma.

   §  Tuple can be empty, Tuple there is no order

   §  Tuple values are Repeated (Duplicate)

 

Syntax for Tuples:

--------------------

  tuple_name = tuple ( (value1, value2, value3,..., valuen) )

 

Example:

-----------

->Empty Tuple:

    tuple1=tuple ()

->Integer Tuple:

    tuple1=tuple ((1,2,3))

->Floating Tuple:

    tuple1=tuple ((1.5,2.5,3.6))

->string Tuple:

    tuple1=tuple (("hello", "welcome", "python"))

->Mixed Tuple:

    tuple1=tuple((1,2.5,"hello"))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Accessing Tuple

------------------

àTuple items are indexed, the first item has index [0], the second item has index [1] etc.

-Forward Index: 0, 1, 2, 3, 4...

      -Backward Index: -1,-2,-3,-4...

Ex:

 str=tuple ((10,20,30,40,50,60))

 str[0]=10=str[-6],

 str[1]=20=str[-5],

 str[2]=30=str[-4],

 str[3]=40=str[-3],

 str[4]=50=str[-2],

 str[5]=60=str[-1].

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Example Program for Display & Accessing Python Tuple

a=tuple ()

b=tuple ((10,20,3,5,8,1))

c=tuple ((10.5,20.5,3.5))

d=tuple (("welcome", "python"))

e=tuple ((12, 5.6, "hello", 25))

print(a)

print(b)

print(c)

print(d)

print(e)

 

a=tuple ((10, 3, 5, 20, 7, 20))

print (a)

print (a[0])

print (a[-1])

print (a[1:3])

print (a[2:])

print (a[:2])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python Tuple Methods

------------------------------

1.count() - Returns the number of elements with the specified value

2.index() - Returns the index of the first element with the specified value

3.min(tuple): Returns the minimum value from the tuple given.

4.max(tuple): Returns the largest value from the given tuple.

5.len(tuple): Returns number of elements in a tuple.

6.Tuple(sequence): Takes sequence types and converts them to Tuples.

7.del : delete a Tuple

8.sum : sum of a tuples

9.sorted : sorted of a tuples

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Example Program for Python Tuples Methods

a=tuple ((20,30,10,15,10,25))

print(a)

print("10 count :",a.count(10))

print("Index :",a.index(10))

print("Max :",max(a))

print("Min :",min(a))

print("Len :",len(a))

print("Sum :",sum(a))

print("Sorted :",sorted(a))

del a

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


 

3. Python Strings

Python Strings:

--------------------

  -String is a collection characters or sequence of character

  -String is noted by single quotes (‘ ‘) or double quotes (“ ”)

  -string is immutable (can’t alter strings)

  -string character stored on sequential order

Syntax:

   Variable = "strings"

    (or)  Variable = ‘strings‘

Ex:

     str1="welcome"

     str2='welcome'

 

Accessing strings

----------------------

  -string character can be access both Forward and backward format

  -Forward Index: 0,1,2,3,4...

  -Backward Index: -1,-2,-3,-4...

Ex:

 str="PYTHON"

 str[0]='P'=str[-6],

 str[1]='Y'=str[-5],

 str[2]='T'=str[-4],

 str[3]='H'=str[-3],

 str[4]='O'=str[-2],

 str[5]='N'=str[-1].

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Example Program Python strings slice notations

str1="welcome to python"

print(str1)

print(str1[0])

print(str1[1])

print(str1[1:])

print(str1[:2])

print(str1[0:2])

str1="hello"

print(str1[::-1]) #olleh

~~~~~~~~~~~~~~~~~~~~~~~~~~~

String Operator:

-------------------

1. Basic Operator

   a. String Concatenation Operator (+)

   b. Replication Operator (*)

2. Membership Operator

   a. in

   b. not in

3. Relational Operator

    <,><=,>=,==,!=

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: String Operators

#using string concatenation operator

str1="welcome"

str2="to python"

str3=str1+" "+str2

print(str3)

 

str1="welcome"

str2=20

#str3=str1+str2  #Error

str3=str1+str(str2)

print(str3)

 

#using string Replication operator

str1="welcome\n"*5

print(str1)

 

#using string Membership operator

str1="welcome to python"

print("welcome" in str1)

print("chennai" in str1)

print("chennai" not in str1)

print("welcome" not in str1)

 

#using string Relational operator

# <,><=,>=,==,!=

str1="jahab"

str2="jahab"

str3="trichy"

print(str1==str2) #true

print(str1==str3) #false

print(str1!=str2) #false

str1="A" #65

str2="a" #97

print(str1!=str2) #true

print(str1==str2) #false

print(str1<str2)  #true

print(str1>str2)  #false

str1="a"

str2="a"

print(str1>str2) #false

print(str1>=str2) #true

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 String Methods

------------------

1. capitalize()

2. count(string,begin,end)

3. endswith(suffix ,begin=0,end=n)

4. find(substring ,beginIndex, endIndex)

5. index(subsring, beginIndex, endIndex)

6. isalnum()

7. isalpha()

8. isdigit()

9. islower()

10.isupper()

11.isspace()

12.len(string)

13.lower()

14.upper()

15.startswith(str ,begin=0,end=n)

16.swapcase()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: using string methods

str1="welcome to msg"

print(str1)

print(str1.capitalize())

str2="msg"

print(str1.count(str2))

print(len(str1))

print(str1.startswith("welcome")) #true

print(str1.startswith("welcometttt")) #false

print(str1.endswith("msg")) #true

print(str1.endswith("msg100")) #false

print(str1.find("msg"))

print(str1.find("msg1")) #-1

print(str1.index('m'))

 

str1="python3.1"

str2="python"

print(str1.isalpha()) #false

print(str2.isalpha()) #true

print(str2.isalnum()) #true

print(str1.isalnum()) #false

 

str1="100"

print(str1.isdigit()) #true

str1="100a"

print(str1.isdigit()) #false

str1="welcome"

str2="WElcome"

str3="WELCOME"

print(str1.islower()) #true

print(str2.islower()) #false

print(str3.isupper()) #true

print(str3.isspace()) #false

str1="welcome"

str2="WELCOME"

print(str1.upper())

print(str1.lower())

print("swap  case")

str1="WElcoMe"

print(str1.swapcase())

print("Left and right Trim")

str1="  welcome"

str2="welcome   "

print(str1)

print(str1.lstrip())

print(str1.rstrip())

str1="welcome to python"

print(str1.replace("to","too"))

print(str1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

4. Python Dictionary

Python Dictionary

-------------------------

·         Dictionaries are used to store data values in key: value pairs.

·         Dictionaries can be referred to by using the key name. [key name not duplicate]

·         A dictionary is a collection which is ordered, changeable.

 

Syntax for Dictionary:

---------------------------

 dic_name = {Key1:Data1, Key2:Data2….} 

 

Example:

->Empty Dictionary:

    dic1={}

->Integer Value Dictionary:

    dic1={100:10,101:5,102:20}

->Floating Value Dictionary:

    dic1={100:10.5,101:5.6,102:20.6}

->string Value Dictionary:

    dic1={1:"hello",2:"welcome",3:"python"}

    dic2={'Name':'jahab','Qualification:M.sc.Mphil','class':1}

->Mixed Value Dictionary:

    dic1={1:1,2:2.5,3:"hello"}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Example Program for Python Dictionary

dic1={}

print(dic1)

dic1={100:10,101:5,102:10,104:1,103:30,103:20}

print(dic1)

dic1={100:10.5,101:5.6,102:20.6}

print(dic1)

dic1={1:"hello",2:"welcome",3:"python"}

print(dic1)

dic1={1:1,2:2.5,3:"hello"}

print(dic1)

#accessing dictionaries data

a1={100:10,101:20,102:30}

a2={'Name':'jahab','Qualification':'M.sc.Mphil','class':1}

a3={1:1000,"Name":"Jahab","Age":30}

print(a1[100])

print(a2['Name'])

print(a3['Age'])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

------------------------------

Python Dictionary Methods

------------------------------

1. update() - Updates the dictionary with the specified key-value pairs 

2. min(dic): Returns the minimum value from the tuple given.

3. max(dic): Returns the largest value from the given dictionary.

4. len(dic): Returns number of elements in a dictionary.

5. clear() : Clear dictionary

6. sum : sum of a Dictionary Values

7.sorted : sorted of a dictionary values

8. pop() Removes the element with the specified key

9. popitem() Removes the last inserted key-value pair

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Example Program for Dictionary Methods

dic1={1:1000,2:1001,7:30,5:2000}

print(dic1)

dic1.update({8:1000})

print(dic1)

print ("Minimum:",min(dic1))

print ("Maximum:",max(dic1))

print ("Length :",len(dic1))

print ("sum :",sum(dic1))

print ("sorting :",sorted(dic1))

print ("Get item :",dic1.get(5))

print(dic1.pop(2))

print(dic1)

print(dic1.popitem())

print(dic1)

dic1.clear()

print(dic1)

del dic1

print(dic1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


 

5. Python sets

Python Set

--------------

   §  Sets are used to store multiple items in a single variable. (duplicates not allowed)

   § set is a collection which is unorderedunindexed and unchangeable but you can remove items and add new items.

   §  Sets are written with curly brackets.

 

Syntax for set:

-----------------

  set_name = set ()

 

Example:

->Empty Set:

    a1=set ()

->Integer Set:

    a1=set ((1,2,3))

->Floating Set:

    a1=set ((1.5,2.5,3.6))

->string Set:

    a1=set (("hello", "welcome", "python"))

->Mixed set:

    a1=set ((1,2.5,"hello"))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Example program for set

a=set ()

print(a)

a1=set ((1,2,3))

print(a1)

a2=set ((1.5,2.5,3.6))

print(a2)

a3=set (("hello", "welcome", "python"))

print(a3)

a4=set((1,2.5,"hello"))

print(a4)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--------------------------------------------

Python set Methods

-------------------------------

1. remove()-Removes Element from the Set

2. add()   -adds element to a set

3. copy()  -Returns Shallow Copy of a Set

4. clear() -remove all elements from a set

5. difference()-Returns Difference of Two Sets

6. discard()-Removes an Element from The Set

7. intersection()-Returns Intersection of Two or More Sets

8. pop()   -Removes an Arbitrary Element

9. union() -Returns Union of Sets

10.update()-Add Elements to The Set.

11.len()   -Returns Length of an Object

12.max()   -returns largest element

13.min()   -returns smallest element

14.set()   -returns a Python set

15.sorted()-returns sorted list from a given iterable

16.sum()   -Add items of an Iterable

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: using Python Set Methods

a=set([10,20,45,5,9,2,78,2])

print (a)

a.add(50)

print (a)

a.update([12])

print (a)

a.discard(12)

print (a)

a.remove(2)

print (a)

print ("Minimum:",min(a))

print ("Maximum:",max(a))

print ("Length :",len(a))

print ("sum :",sum(a))

print ("sorting :",sorted(a))


a.clear()

print (a)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Example Program for set Operations

A = set([1, 2, 3, 4, 5])

B = set([4, 5, 6, 7, 8])

print (A)

print (B)

print (A|B)

print (A.union(B))

print (A&B)

print (A.intersection(B))

print (A-B)

print (A.difference(B))

myset=set("apple")

print ('a' in myset)

print ('c' in myset)

print ('c' not in myset)

print ('a' not in myset)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

 

No comments:

Post a Comment