Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
511 views11 pages

PYTHON Chapter 2 PDF

The document discusses various Python string, list, tuple, and dictionary functions and operations. It provides examples of using string functions like lstrip() and rstrip() to remove leading and trailing characters. It also demonstrates how to create, traverse, slice, manipulate, and sort lists, tuples, and dictionaries in Python. Various list functions like append(), insert(), pop(), reverse() are shown. The document also discusses the differences between lists and tuples, and provides examples of tuple operations and functions.

Uploaded by

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

PYTHON Chapter 2 PDF

The document discusses various Python string, list, tuple, and dictionary functions and operations. It provides examples of using string functions like lstrip() and rstrip() to remove leading and trailing characters. It also demonstrates how to create, traverse, slice, manipulate, and sort lists, tuples, and dictionaries in Python. Various list functions like append(), insert(), pop(), reverse() are shown. The document also discusses the differences between lists and tuples, and provides examples of tuple operations and functions.

Uploaded by

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

PYTHON REVISION TOUR II

STRING FUNCTIONS:

1. string.lstrip(): Returns a copy of the string with leading characters removed.


e.g. >>>str= “there” output:
>>>str.lstrip(“the”) “re”
[matching strings like ‘t’, ‘th’ etc are removed from left of the string]
2. string.rstrip(): returns a copy of the string with trailing characters removed.
e.g. >>>str.rstrip(“care”) output
“th”

Do it at your own:

WAP which reads a line and print statistics like:

Number of uppercase letters:

Number of lowercase letters:

Number of alphabets:

Number of digits:

LISTS IN PYTHON

A list is a data type in python storing sequence of values separated by commas


and enclosed in square brackets. It is mutable data type. E,g. [1,2,3]

Creating empty list

L=list()

Creating list from existing sequences

L=list(“hello”)

>>>L

[‘h’, ’e’, ’l’, ’l’, ’o’]


Creating list from keyboard input:

L= list(input(“Enter list elements:”))

Enter list elements:234567

>>>L

[‘2’,’3’,’4’,’5’,’6’,’7’] #by default string came as output]

To enter list of integers:

L= eval(input(“Enter list elements:”))

Enter list elements:234567

>>>L

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

Difference between Lists and strings:

1. Lists are stored in memory exactly like strings, only difference is that list
store a reference at each index instead of a single character as in strings.
2. Lists are mutable but strings are immutable.

LIST OPERATIONS:

1. Traversing a List: Processing each element of the list


L= [‘P’, ‘Y’, ‘T’,’H’,’O’,’N’]
for a in L
print (a, end=” ”)
output:
PYTHON
2. Joining lists: concatenation operator is used to join lists.
>>>L1=[1,3,9]
>>>L2=[6,12,15]
L1+L2
[1, 3,9,6,12,15]
3. Replicating list: Repeating a list that many number of times

>>>L1*3

[1,3,9,1,3,9,1,3,9]

4. Slicing the list: Extracting a sub part of the string


Seq=L[start:stop]
E.g.>>> L= [20,21,22,23,25,26,29,30]
>>>seq=L[3:5]
>>>seq
[23,25]
LIST MANIPULATION
1. Appending elements to a List: the append () method/ function is used to
add the items at the end of the list.
>>>L=[10,12,14]
>>>L.append(16)
>>>L
[10,12,14,16]
2. Updating elements to a List: to change an element in place in a list
>>>L=[10,12,14,16]
>>>L[0]=5
>>>L
[5,12,14,16]
3. Deleting elements from a List: del statement is used to delete an element
>>>L=[10,12,14,16]
>>>del L[2]
>>>L
[10,12,16]

MAKING TRUE COPY OF A LIST

Only using assignment operator does not make a copy of the list

e.g. colors=[‘red’,’blue’,’green’]
b=colors #does not copy the list

b=list(colors) #Now colors and b are separate lists(true copy)

LIST FUNCTIONS

1. index method: returns the index of first matched item from the list
>>>L=[10,12,14,16]
>>>L.index(12)
1
2. append method: adds an item to the end of the list
>>>L=[10,12,14,16]
>>>L.append(18)
>>>L
[10,12,14,16,18]
3. extend method: used to add multiple elements(in form of list) to the list.
>>>L=[10,12,14,16]
>>>L1=[20,21,22]
>>>L.extend(L1) # argument is a list
>>>L
[10,12,14,16,20,21,22]
4. insert method: inserts an item at a given position
>>>L=[10,12,14,16]
>>>L.insert(3,15) #insert(pos, item)
>>>L
[10,12,14,15,16]
5. pop method: used to remove an item from the list using index
List.pop(index)
>>>L=[10,12,14,16]
>>>e=L.pop(0)
>>>e
10
6. remove method: used to remove first occurrence of given item from list.
List.remove(value)
>>>L=[10,12,14,16]
>>>L.remove(10) #first occurrence of passed value will be removed.
>>>L
[12,14,,16]
7. clear method: remove all items from the list and make it empty
>>>L=[10,12,14,16]
>>>L.clear()
>>>L
[]
For deleting the list del <list> statement to be used
8. count method: returns the count of item passed as argument. if item is not
in the list, returns 0
>>>L=[18,20,15,20,24,20]
>>>L.count(20)
>>>3
9. reverse method: it reverse the items in the list
>>>L=[10,12,14,16]
>>>L.reverse()
>>>L
[16,14,12,10]
10.sort method: sorts the items in the list
>>>L=[10,9,14,16]
>>>L.sort()
>>>L
[9, 10,14,16]

TUPLES IN PYTHON

A TUPLE is a data type in python storing sequence of values separated by commas


and enclosed in parenthesis. It is immutable data type. E,g. (1,2,3)

Creating empty tuple


T=tuple()

Creating tuple from existing sequences

T=tuple(“hello”)

>>>T

(‘h’, ’e’, ’l’, ’l’, ’o’)

Creating tuple from keyboard input:

T= tuple(input(“Enter tuple elements:”))

Enter tuple elements:234567

>>>T

(‘2’,’3’,’4’,’5’,’6’,’7’) #by default string came as output]

To enter list of integers:

L= eval(input(“Enter tuple elements:”))

Enter tuple elements:234567

>>>T

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

Difference between Tuples and Lists

Tuples are immutable while lists are mutable

e.g. L[i]= element #valid for list

T[i]= element #invalid for tuple

TUPLE OPERATIONS

1. Traversing a Tuple: Processing each element of the tuple


T= (‘P’, ‘Y’, ‘T’,’H’,’O’,’N’)
for a in T
print (a, end=” ”)
output:
PYTHON
2. Joining tuples: concatenation operator is used to join tuples.
>>>T1=(1,3,9)
>>>T2=(6,12,15)
T1+T2
(1, 3,9,6,12,15)
3. Replicating tuples: Repeating a tuple that many number of times

>>>T1*3

(1,3,9,1,3,9,1,3,9)

4. Slicing the tuple: Extracting a sub part of the string


Seq=T[start:stop]
E.g.>>> T= (20,21,22,23,25,26,29,30)
>>>seq=T[3:5]
>>>seq
(23,25)
5. Unpacking tuples: creating individual elements from a tuple
e.g. t= (1,2,’a’,’b’)
w,x,y,z =t # four elements in tuple
print(w, ”_” , x, ”_”, y, “_”,z)
1_2_a_b
TUPLE FUNCTIONS
1. len() method: returns the length of the tuple

>>>T=(1,2,3,4,5)

>>>len(T)

5
2. max() method:returns the maximum element from the tuple

>>>T=(1,2,3,4,15)

>>>max(T)

15

3. min() method: returns the minimum element from the tuple


>>>T=(1,2,3,4,15)
>>>min(T)
1

4. index() method: returns the index of existing element


>>>T=(1,2,3,4,15)
>>>T.index(3)
2
5. count() function: returns the count of an element in the tuple
>>>T=(1,2,3,4,3)
>>>T.count(3)
2
6. tuple() method: constructor method to create tuples from diff. values
>>>t=tuple(“abc”)
>>>t
(‘a’ , ‘b’, ‘c’)

Dictionaries in PYTHON
It is an unordered collection of elements in the form of key-value pairs
that associate keys to values. Dictionaries are mutable.
Creating a dictionary
Emp= {“john”: 25000, “blake”:30000, “smith”:40000}
Key are : john, blake and smith
Corresponding values are: 25000,30000 and 40000
Updating existing elements in a dictionary
>>>Emp[“john”]=50000
>>>Emp
{“john”: 50000, “blake”:30000, “smith”:40000}

Deleting elements from a dictionary


>>>del Emp[“blake”]
>>>Emp
{“john”: 25000, “smith”:40000}
pop() method is also used to delete key value pair but it returns the
corresponding value
>>>Emp.pop(“blake”)
30000
>>>Emp
{“john”: 25000, “smith”:40000}
Checking for existence of a key
>>>”smith” in Emp
True
Dictionary Functions and methods
1. len() method: returns the length of dictionary
>>>len(Emp) # before deletion
3
2. clear() method:It clears all the elements and dictionary becomes empty
>>>Emp.clear()
>>>Emp
{}
3. get() method: to get the item with the given key
>>>Emp.get(“smith”)
40000
4. items() method: to return all the items of dictionary as a sequence of
tuples.
myList=Emp.items()
for x in myList:
print(x)
5. keys() method: return the keys of dictionary in the form of a List
>>>Emp.keys()
[“john”,“blake”, “smith”]
6. values() method: return the values of dictionary in the form of a List
>>>Emp.values()
[50000,30000,40000]
7. update() method:The items in the new dictionary are added to the old one
and override any items already there with the same keys.
Emp1= {“john”: 25000, “blake”:30000, “smith”:40000}

Emp2= {“kevin”: 50000, “lalit”:30000, “smith”:25000}

>>>Emp1.update(Emp2)
>>>Emp1
Emp1= {“john”: 25000, “blake”:30000, “smith”:25000, “kevin”: 50000,
“lalit”:30000}

WAP that checks for presence of a value inside a dictionary and print its
key.
Sol. Info={“Riya”:”Csc.”, “Mark”:”Eco”,”Ishpreet”:”Eng”,”Kamaal”:”EVS”}
inp=input(“enter the value to be searched for”)
if inp in info.values():
for a in info:
if info[a]==inp:
print(“The key of given value is”,a)
break
else:
print(“Given value does not exist in the dictionary”)
SORTING TECHNIQUES
SORTING: Arranging elements in a specific order ascending or descending.
1. Bubble Sort:The basic idea of bubble sort is to compare two adjoining
values and exchange them if they are not in proper order.
Program to sort a list using Bubble Sort
aList=[15,6,13,22,3,52,2]
print(“orginal list is:”, aList)
n=len(aList)
for i in range(n):
for j in range(0,n-i-1):
if aList[j]>aList[j+1]:
aList[j],aList[j+1]=aList[j+1],aList[j]
print(“List after sorting”, aList)
2. Insertion Sort: It is a sorting algorithm that builds a sorted list one
element at a time from the unsorted list by inserting the element at its
correct position in the sorted list.
Program to sort a sequence using insertion sort.
Sol. aList=[15,6,13,22,3,52,2]
print(“orginal list is:”, aList)
for in range(1,len(aList)):
key=aList[i]
j=i-1
while j>=0 and key< aList[j]:
aList[j+1]= aList[j]
else:
aList[j+1]=key
print(“List aftersorting”,aList)

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

You might also like