Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Sem 3python Module IV Final

This document summarizes key concepts about strings and lists in Python. It discusses how to create, access, modify, and perform common operations on strings and lists. For strings, this includes indexing, slicing, string methods like lower() and upper(), and string formatting. For lists, it covers creation, accessing elements, updating/deleting elements, basic operations like concatenation and membership testing, and list methods like insert(), sort(), and reverse().

Uploaded by

asnaph9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Sem 3python Module IV Final

This document summarizes key concepts about strings and lists in Python. It discusses how to create, access, modify, and perform common operations on strings and lists. For strings, this includes indexing, slicing, string methods like lower() and upper(), and string formatting. For lists, it covers creation, accessing elements, updating/deleting elements, basic operations like concatenation and membership testing, and list methods like insert(), sort(), and reverse().

Uploaded by

asnaph9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module IV

Collection or Sequence datatypes(Dynamic Data Structures)


String
A string is a sequence of characters. In Python, a string is a sequence of
Unicode characters.
na=“Good morning”
Creating a string
To create a string include them within single quotes, double quotes and
triple quotes(for multiline).
Example
na1=‟bca‟
print("String1 :",na1)
na2="Bsc"
print("String2 :",na2)
na3="""Semester3
Subjects"""
print("String3 :",na3)
Output
String1 : bca
String2 : Bsc
String3 : Semester3
Subjects
Displaying a String
1.Iteration
The For Loop is the most common way to traverse/iterate the characters
or items.
na=‟Computer‟
for na in name:
print(na)
Output
C
o
m
p
u
t
e
r
2. Indexing
We can use the index operator [] to access a character from a string,
where the index starts from 0. Trying to access an index outside of the
String index range will raise an IndexError. The index must be an
integer, so we cannot use float or other types.
2. Negative Indexing
Python allows negative indexing for strings. The index of -1 refers to the
last item, -2 to the second last item and so on.
3. Slicing
[:] is known as range slice operator. It is used to access the characters
from the specified range.
[startindex:endindex]
 If you omit the first index, the slicing starts from the beginning.
 If you omit the second argument, Slicing starts from the first
position and continues to the last.
 And, If you are using the Negative numbers as an index, the slicing
starts from right to left.
Example
na="welcome"
print("String :",na)
print("Chartacer from index3 :",na[3])
print("Chartacer from last position :",na[-1])
print("Substring :",na[3:])
print("Substring :",na[0:2])
Output
String : welcome
Chartacer from index3 : c
Chartacer from last position : e
Substring : come
Substring : we
String Concatenation
Joining or combining more than one is called as the Python string
concatenation or concat.
 We can use + operator to join more than one.
 By placing more than one literal, joins them automatically.
 Placing more than one inside parentheses ()
 * operator is repeating the sentence for a given number of times.
Example
na1 = 'BCA '
na2 = 'BSc'
name1 = na1+na2
name2 = 'Computer Science '
name3 = ('Degree ' 'Course')
name4=na1*4
print("Merged String :",name1)
print("Merged String :",name2)
print("Merged String :",name3)
print("Merged String :",name4)
Output
Merged String : BCA BSc
Merged String : Computer Science
Merged String : Degree Course
Merged String : BCA BCA BCA BCA
Membership operator(in and not in)
String Membership Test : We can test if an item/character exists in a
string or not, using the keyword in and not in. It returns True or False.
Example:
na="computer"
print("String :",na);
print("Membership operator :","m" in na)
print("Membership operator :","m" not in na)
Output
String : computer
Membership operator : True
Membership operator : False
Method and Functions
Methods are associated with the objects of the class. Functions are not
associated with any object.
String functions
len(string) : Returns length of string .
max(str) : Returns the max alphabetical character from the string str.
min(str) : Returns the min alphabetical character from the string str.
String Methods
String.capitalize() :Capitalizes first letter of string
String.count(str, beg= 0,end=len(string)) : Counts how many times str
occurs in string or in a substring of string if starting index beg and
ending index end are given.
String.islower(): Returns true if string has at least 1 cased character and
all cased characters are in lowercase and false otherwise.
String.isupper(): Returns true if string has at least one cased character
and all cased characters are in uppercase and false otherwise.
String.join(seq): Merges (concatenates) the string representations of
elements in sequence seq into a string, with separator string.
String.lower() : Converts all uppercase letters in string to lowercase.
String.lstrip(): Removes all leading whitespace in string.
String.replace(old, new [, max]): Replaces all occurrences of old in
string with new or at most max occurrences if max given.
String.rstrip() :Removes all trailing whitespace of string.
String. upper() : Converts lowercase letters in string to uppercase.
Example
na="computer"
print(na)
print("no of characters :",len(na));
print("Max :",max(na));
print(na.count("m",0))
print(na.index("put"))
l1=["sheela", "Martin","NCAS"]
s="**"
print(s.join(l1))
print(na.lower())
print(na.upper())
a=" hello "
print(len(a))
print(len(a.lstrip()))
print(len(a.rstrip()))
print(len(a.strip()))
print(na.replace("puter","p"))
output
computer
no of characters : 8
Max : u
1
3
sheela**Martin**NCAS
computer
COMPUTER
9
7
7
5
comp
Formatting Strings using format()
The format() method that is available with the string object is very
versatile and powerful in formatting strings. Format strings contain curly
braces {} as placeholders or replacement fields which get replaced. We
can use positional arguments or keyword arguments to specify the order.
Example
st1 = "{}, {} and {}".format("Computer Science","BCA","B.Sc")
print("Given string :",st1)
# order using positional argument
st2= "{1}, {2} --- {0} ".format("Computer Science","BCA","B.Sc")
print(" Positional Order :",st2);
# order using keyword argument
st3 = "{c}, {b}--{a}".format(a="Computer
Science",b="BCA",c="B.Sc")
print("Keyword Order :",st3);
Output
Given string : Computer Science, BCA and B.Sc
Positional Order : BCA, B.Sc --- Computer Science
Keyword Order : B.Sc, BCA--Computer Science
List
A list is a collection of values or items of different types. The items in
the list are separated with the comma (,) and enclosed with the square
brackets []. List items are ordered, changeable, and allow duplicate
values. List items are indexed, the first item has index [0], the second
item has index [1] etc. When we say that lists are ordered, it means that
the items have a defined order, and that order will not change. If you add
new items to a list, the new items will be placed at the end of the list.
Creating list
L1 = [10,"John", "BCA"]
L2 = [1, 2, 3, 4, 5, 6]
Accessing list
We can use the index operator [] to access a character from a string,
where the index starts from 0. Trying to access an index outside of the
String index range will raise an IndexError. The index must be an
integer, so we cannot use float or other types.
2. Negative Indexing
Python allows negative indexing for strings. The index of -1 refers to the
last item, -2 to the second last item and so on.
3. Slicing
[:] is known as range slice operator. It is used to access the characters
from the specified range.
[startindex:endindex]
Example
l1=[1,"Anu",300,500]
print("Items from list :",l1)
print("List using for loop")
for na in l1:
print(na)
print("Indexing :",l1[1])
print("Indexing :",l1[-2])
print("Slicing :",l1[1:3])
Output
Items from list : [1, 'Anu', 300, 500]
List using for loop
1
Anu
300
500
Indexing : Anu
Indexing : 300
Sliciing : ['Anu', 300]
Updating a list
You can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to
elements in a list with the append() method.
Updating element using index number.
User can update item in a list using index operator.
Syntax:
list[<index>]=<new value>
Example
l1=[10,"a",50]
print("List :",l1)
l1[2]=100
print("List after updation :",l1)
output
List : [10, 'a', 50]
List after updation : [10, 'a', 100]
Updating element using slice operator.
User can update items in a list using slice operator(:).
list[<startindex>:<endindex>]=[<new value>,<new value>….]
Example
l1=[10,"a",50,60]
print("List :",l1)
l1[1:3]=[500,500]
print("List after updating elements :",l1)
l1[1:3]=[500,6,7,8]
print("List after updating elements :",l1)
output
List : [10, 'a', 50, 60]
List after updating elements : [10, 500, 500, 60]
List after updating elements : [10, 500, 6, 7, 8, 60]
Updating element using append()
append(): Adds a new entry to the end of the list.
Syntax:
List.append(item)
l1=[10,"a",50,60]
print("List :",l1)
l1.append(200)
print("List after updation :",l1)
l2=[500]
l1.append(l2)
print("List after updation :",l1)
output
List : [10, 'a', 50, 60]
List after updation : [10, 'a', 50, 60, 200]
List after updation : [10, 'a', 50, 60, 200, [500]]
Deleting List
list.clear() : The clear() method removes all items from the list.
Syntax:
Example
l1=[10,"a",50,60]
print("List :",l1)
l1.clear()
print("List after clearing elements :",l1)
output
List : [10, 'a', 50, 60]
List after clearing elements : []
Basic list operations
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration
List functions
len(string) : Returns length of list.
max(str) : Returns the max number from the list.
min(str) : Returns the min number from the list
Example
l1=[1,"Anu",300,500]
print("No of items in list :",len(l1))
l1=[1,300,500]
print("largest item in list :",max(l1))
print("Smallest item in list :",min(l1))
Output
No of items in list : 4
largest item in list : 500
Smallest item in list : 1
List methods
list.insert(i, x) : Insert an item at a given position. The first argument is
the index of the element before which to insert, so a.insert(0, x) inserts at
the front of the list.
list.count(x) : Return the number of times x appears in the list.
list.sort() : Sort the items of the list in place
list.reverse() : Reverse the elements of the list in place.
Example
l1=[1,"Anu",300,500]
l1.insert(0,1001)
print("Inserted list :",l1)
l2=[20,10,40,30]
print("List :",l2)
l2.sort()
print("Sorted list :",l2)
l2.reverse()
print("Reversed list",l2)
Output
Inserted list : [1001, 1, 'Anu', 300, 500]
List : [20, 10, 40, 30]
Sorted list : [10, 20, 30, 40]
Reversed list : [40, 30, 20, 10]
Tuple
A Tuple is a collection of Python objects separated by comma. A tuple
is a collection of sequences which is ordered and immutable. The
differences between tuples and lists are, lists can be changed and the
tuples cannot be changed. List use square brackets, whereas Tuples use
parentheses. Tuples can be thought of as read-only lists.
Creating a Tuple
To create a tuple include values between parentheses using comma as a
separator.
Example
t1=(101,"bca",500)
print("Tuple :",t1)
print("Type of t1 :",type(t1))
t2=()
print("Tuple :",t2)
Output
Tuple : (101, 'bca', 500)
Type of t1 : <class 'tuple'>
Tuple : ()
A tuple can also be created without using parentheses. This is known as
tuple packing.
Example
t1=10,"bca",500
print(t1)
print(type(t1))
Output
(10, 'bca', 500)
<class 'tuple'>
Accessing Values from Tuples
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index.
Indexing
We can use the index operator [] to access an item in a tuple, where the
index starts from 0.So, a tuple having 3 elements will have indices from
0 to 2. Trying to access an index outside of the tuple index range(3,4,...
in this example) will raise an IndexError. The index must be an integer,
so we cannot use float or other types. This will result in TypeError.
2. Negative Indexing
Python allows negative indexing for tuples. The index of -1 refers to the
last item, -2 to the second last item and so on.
3. Slicing
We can access a range of items in a tuple by using the slicing operator
colon :
Basic Tuple operations
We can use + operator to combine two tuples. This is
called concatenation. We can also repeat the elements in a tuple for a
given number of times using the * operator.
Both +(concatenation) and * (Repetition) operations result in a new
tuple.
Example
t1=(10,20)
t2=(40,50)
t3=t1+t2
print("Tuple 1:",t1)
print("Tuple 2:",t2)
print("Tuple 3:",t3)
t4=t1*2
print("Tuple 4 :",t4)
Output
Tuple 1: (10, 20)
Tuple 2: (40, 50)
Tuple 3: (10, 20, 40, 50)
Tuple 4 :(10, 20, 10, 20)
Membership & Iteration
Tuple Membership Test : We can test if an item exists in a tuple or not,
using the keyword in and not in . It returns True or False.
Iteration: We can use a for-in loop to iterate through each item in a
tuple.
t1=(1,"Anu",20,30,20)
print("Item status :", 20 in t1)
print("Items from Tuple ")
for x in t1:
print(x)
Output
Item status : True
Items from Tuple
1
Anu
20
30
20
Updating Tuples
Tuples are immutable which means you cannot update or change the
values of tuple elements.
Deleting Tuple Elements
Removing individual tuple elements is not possible. To remove an
entire tuple, use the del statement.
Example
t1=(1,"Anu",20,30,20)
print("Tuple",t1)
del t1
output
Tuple (1, 'Anu', 20, 30, 20)
Built-in Tuple Functions
len(tuple) :Returns length of the tuple.
max(tuple): Returns max value.
min(tuple): Returns min value.
Example
t1=(101,25,25.0,101.2)
print("Tuple 1",t1)
print("No of elements in Tuple :",len(t1))
print("Largest :",max(t1))
print("Smallest :",min(t1))
Output
Tuple 1 (101, 25, 25.0, 101.2)
No of elements in Tuple : 4
Largest : 101.2
Smallest : 25
Difference between List and Tuple
List is mutable. Tuple is immutable.

List is useful for insertion and Tuple is useful for read only
deletion operations. operations like accessing elements.

List consumes more memory. Tuples consumes less memory.


List provides many in-built Tuples have less in-built methods.
methods.
Dictionary
Dictionary in Python is an unordered collection of data values.
Dictionary holds key:value pair for storing elements.
Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements
within curly {} braces, separated by „comma‟. Dictionary holds a pair of
values, one being the Key and the other corresponding pair element
being its Key:value. Values in a dictionary can be of any data type and
can be duplicated.
Rules for creating keys
 A key must be unique in dictionary
 Dictionary keys are case sensitive.
Example
d1={1:"BCA",2:"B.Sc",11:"B.Com",21:"BBA"}
print("Dictionary 1:",d1)
print("Type :",type(d1))
d2={1:101,2:"MCA"}
print("Dictionary 2:",d2);
print("Item using key :",d1[11])
Output
Dictionary 1: {1: 'BCA', 2: 'B.Sc', 11: 'B.Com', 21: 'BBA'}
Type : <class 'dict'>
Dictionary 2: {1: 101, 2: 'MCA'}
Item using key : B.Com
Removing elements from Dictionary
We can remove a particular item in a dictionary by using
the pop() method. This method removes an item with the
provided key and returns the value. The popitem() method can be used
to remove and return an arbitrary (key, value) item pair from the
dictionary. All the items can be removed at once, using
the clear() method. We can also use the del keyword to remove
individual items or the entire dictionary itself.
Methods for accessing Dictionary values
Using For loop: use for in loop to access keys and values.
Example
d1={ 'No':101,'Name':'Degree','Year':3,100:"A"}
for x in d1:
print(x,":",d1[x])
Output
No : 101
Name : Degree
Year : 3
100 : A
Using keys : - You can access the items of a dictionary by referring to
its key name, inside square brackets:
Using dictionary.get(): You can access the items of a dictionary by
referring to its key name, inside square brackets:
Using dictionary.keys(): -The keys() method will return a list of all the
keys in the dictionary.
Using dictionary.values():The values() method will return a list of all
the values in the dictionary.
Using dictionary.items():The items() method will return each item in a
dictionary, as tuples in a list.
Using if-in : To determine if a specified key is present in a dictionary
use the in keyword:
Example
d1={ 'No':101,'Name':'Degree','Year':3,100:"A"}
print("Dictionary :",d1)
print("Using keys",d1[100])
print("Using keys",d1['No'])
print("Using get()",d1.get('No'))
print("Keys from Dictionary using keys()",d1.keys())
print("Values from Dictionary using values()",d1.values())
print("Values from Dictionary using items()",d1.items())
if 'name' in d1:
print("Key existing")
else:
print("Key existing")
Output
Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3, 100: 'A'}
Using keys A
Using keys 101
Using get() 101
Keys from Dictionary using keys() dict_keys(['No', 'Name', 'Year', 100])
Values from Dictionary using values() dict_values([101, 'Degree', 3,
'A'])
Values from Dictionary using items() dict_items([('No', 101), ('Name',
'Degree'), ('Year', 3), (100, 'A')])
Key existing
Methods for updating Dictionary values
Using dictionary.update(): The update() method inserts the specified
items to the dictionary.
d1={ 'No':101,'Name':'Degree','Year':3,100:"A"}
d2={'Mark':400}
print("Dictionary :",d1)
d1.update(d2)
print("Dictionary :",d1)
print("Dictionary :",d2)
Output
Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3, 100: 'A'}
Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3, 100: 'A', 'Mark': 400}
Dictionary : {'Mark': 400}
Methods for deleting Dictionary values
Using dictionary.pop() :The pop() method removes the item with the
specified key name:
Using dictionary.popitem(): The popitem() method removes the last
inserted item .
Using del: del keyword removes the item with the specified key name.
The del keyword can also delete the dictionary completely:
Using dictionary.clear(): The clear() method empties the dictionary.
Example
d1={ 'No':101,'Name':'Degree','Year':3,100:"A"}
print("Dictionary :",d1)
print("Deletion using pop() :",d1.pop(100))
print("After deletion Dictionary :",d1)
print("Deletion using popitem() :",d1.popitem())
print("After deletion Dictionary :",d1)
del d1['No']
print("After deletion Dictionary :",d1)
del d1
d2={ 'No':101,'Name':'Degree','Year':3,100:"A"}
print("Dictionary :",d2)
print("Deletion using clear() :",d2.clear())
print("After deletion Dictionary :",d2)
Output
Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3, 100: 'A'}
Deletion using pop() : A
After deletion Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3}
Deletion using popitem() : ('Year', 3)
After deletion Dictionary : {'No': 101, 'Name': 'Degree'}
After deletion Dictionary : {'Name': 'Degree'}
Dictionary : {'No': 101, 'Name': 'Degree', 'Year': 3, 100: 'A'}
Deletion using clear() : None
After deletion Dictionary : {}
Set
A Set is is a collection which is unordered and unindexed data type that
is iterable, mutable and has no duplicate elements. Sets are unordered ,
so you cannot be sure in which order the items will appear. Python‟s set
class is used for mathematical operations like union, intersection,
difference and complement etc. Set has a highly optimized method for
checking whether a specific element is contained in the set or not. This
is based on a data structure known as a hash table. The elements in the
set cannot be duplicates. The elements in the set are immutable(cannot
be modified) but the set as a whole is mutable. There is no index
attached to any element in a python set. So they do not support any
indexing or slicing operation.
Creating a set
A set is created by placing all the items (elements) inside curly
braces {}, separated by comma, or by using the built-in set() function. It
can have any number of items and they may be of different types
(integer, float, tuple, string etc.).
Example
s1={10,20,30};
print("Set 1:",s1)
print("Type of set1 :",type(s1))
s 2={10,20,30,30,50,60};
print("Set2 :",s2)
s3={} # it becomes dictionary
s3=set() #empty set
print("Set3 :",s3)
print(type(s3))
s4=set([1,"BCA",50.0])
print("Set 4 :",s4)
s5=set((1,2,3))
print("Set5 :",s5)
print(type(s5))
Output
Set 1: {10, 20, 30}
Type of set1 : <class 'set'>
Set2 : {10, 50, 20, 60, 30}
Set3 : set()
<class 'set'>
Set 4 : {1, 50.0, 'BCA'}
Set5 : {1, 2, 3}
<class 'set'>
Accessing Values from a Set
We cannot access individual values in a set. So indexing and slicing is
not available with set. We can only access all the elements together.
But we can also get a list of individual elements by looping through the
set.
Example
s1={10,20,30};
print ("Set :",s1);
print("Elements from index :")
for x in s1:
print(x)
Output
Set : {10, 20, 30}
Elements from index :
10
20
30
Adding Items to a Set
We can add elements to a set by using add() method.
Example
s1={1,"UG","BCA"};
print ("Set :",s1);
s1.add(2);
print ("Set :",s1);
Output
Set : {1, 'BCA', 'UG'}
Set : {2, 1, 'BCA', 'UG'}
Removing Item from a Set
We can remove elements from a set by using discard() method.
Example
s1={1,"UG","BCA"};
print ("Set :",s1);
s1.discard("BCA");
print ("Set :",s1);
Output
Set : {'UG', 1, 'BCA'}
Set : {'UG', 1}
Set operations
Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference.
1. Union of Sets
The union operation on two sets produces a new set containing all the
distinct elements from both the sets. Union is performed using | operator
and union() method.

Example
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Set 1 :",A);
print("Set 2 :",B);
print("Set of union using | :",A|B)
print("Set of union using union() :",A.union(B))
Output
Set 1 : {1, 2, 3, 4, 5}
Set 2 : {4, 5, 6, 7, 8}
Set of union using | : {1, 2, 3, 4, 5, 6, 7, 8}
Set of union using union() : {1, 2, 3, 4, 5, 6, 7, 8}
2. Intersection of Sets
The intersection operation on two sets produces a new set containing
only the common elements from both the sets. Intersection is performed
using & operator and intersection() method.

Example
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Set 1 :",A);
print("Set 2 :",B);
print("Set of intersection using &:",A&B)
print("Set of intersection using intersection() :",A.intersection(B))
Output
Set 1 : {1, 2, 3, 4, 5}
Set 2 : {4, 5, 6, 7, 8}
Set of intersection using &: {4, 5}
Set of intersection using intersection() : {4, 5}
3. Difference of Sets
The difference operation on two sets produces a new set containing only
the elements from the first set and none from the second set. A(A-B) is
a set of elements that are only in A but not in B. Similarly, B -A is a set
of elements in B but not in A. Difference is performed using – operator
and difference() method.
Example
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Set 1 :",A);
print("Set 2 :",B);
print("Set of Difference (A-B) - :",A-B)
print("Set of Difference using difference() :",A.difference(B))
print("Set of Difference (B-A) - :",B-A)
print("Set of Difference using difference() :",B.difference(A))
Output
Set 1 : {1, 2, 3, 4, 5}
Set 2 : {4, 5, 6, 7, 8}
Set of Difference (A-B) - : {1, 2, 3}
Set of Difference using difference() : {1, 2, 3}
Set of Difference (B-A) - : {8, 6, 7}
Set of Difference using difference() : {8, 6, 7}
**************

You might also like