Python Rivision Tour-2
Python Rivision Tour-2
STRINGS
A sequence of characters is called a string.
manipulate text such as words and sentences.Strings are used byprogramming languages to
Strings literal in Python are enclosed by
span multiple lines, to write these stringsdouble quotes or single quotes. String literals can
>>>a= "Python triple quotes are used.
Empty string can also be created in
Programming
Language'** Python.
>>>str =*
Accessing Values in Strings
Each individual character in a string can be assessed
Python allows both positive and negative indexing. using a technique called indexing.
S="Python Language"
3 4 6 7 10 12 13
P h L a n a
-15 -14 -13 -12 -|| -10 -9 -8 -7 -6 -5 -4 -3 -2
>>> S[7)
>>>S[-10)
Deleting a String n
LIST
data at the same time. List
List is an ordered sequence, which is used to store multiple
contains a sequence of heterogeneous elements. Each elementindex of alist is assigned a number
is 1 ,the third index is 2
to its position or index. The first index is 0 (zero), the second
and so on.
Creating a List In Python,
a=[34,76, 11,98]
b=['s',3,6,'t']
d=(0
Creating List From an Existing Sequence: list () method is used to create list from an
existing sequence. Syntax: new_list _name =list ( sequence / string )
You can also create an empty list . eg. a = list().
Similarity between List and String
len ( ) function is used to return the number of items in both list and string.
Membership operators as in and not in are same in list as well as string.
Concatenation and replication operations are also same done in list and string.
Diference between String and List
Strings are immutable which means the values provided to them will not change in the
program. Lists are mutable which means the values of list can be changed at any time.
Accessing Lists
To access the list's elements, index number is used.
S=[12,4,66,7,8,97, "computer",5.5,] 0 2 3 4 5 6 7
>>> S[5]
10
Page 97 12 4 66 7 8 97 computer 5.5
>>>S[-2] -8 -7 -6 -5 -4 -3 -2
computer
Traversing a List
Traversing a list is a technique to access an individual element of that list.
1. Using for loop for loop is used when you want to traverse each element of alist.
>>>a=[p','r,'o.'g'.'r','a','m']
>>> fot x in a:
print(x, end = ) output : program
2. Using for loop with range( )
>>>a=['p.r',;o'.'g'.'r,'a','m']
>>> fot x in range(len(a)):
print(x, end = ) output : progra m
List Operations
1. Concatenate Lists
List concatenation is the technique of combining two lists. The use of +operator can easily
add the whole of one list to other list.Syntax list listl+list2 e.g. >>>Ll=[43, 56.34 ]
>>> L2 =|22, 34, 98 ]
2. Replicating List >>>L= || + 12
Elements of the list can be replicated using * operator >>>L[43, 56. 34, 22, 34,98 ]
Syntax list =list| * digit e.g. >>> LI=[3.2,6]
>>>L= 1|2
>>>L [3.2.6,3,2,6]
3. Slicing of a List: List slicing refers to access a specific portion or a subset of the list for
some operation while the original list remains unaffected
Syntax:- list_name [ start: end ] Syntax: list_name [ start: stop : step ]
>>> Listl =[4,3,7,6,4,9,5,0,3, 2] >>> Listl =[4.3.,7.6.4.9.5,0.3, 2]
>>> S=Listl[ 2:5 ] >>>S=istl[ 1 :9:3]
>>>S >>>
TUPLES
sequence of
is an ordered sequence of elements of different data types. Tuple holds a
A tuple elements and do not allow changes
heterogencous elements, it store a fixed set of
Tuple vs List elements of alist are mutable.
Elements of a tuple are immutable whereas
Tuples are declared in parentheses () while lists are declared in square brackets (].
aster compared to iterating over a list.
Iterating over the elements of atuple is
Creating a Tuple
in parentheses ( ). separated by commas.
To create a tuple in Python, the elements are kept
a=(34,76. 12,90 )
b=('s',3,6,'a')
of tuples, Replication oftuples
Accessing tuple elements, Traversing a tuple, Concatenation
and slicing of tuples works same as that of List
BUILT IN TUPLE METHODS
Method Description
Argument
len() Returns the length or the number ofelements of the tuple passed as
sequence is
tuple() Creates an empty tuple if no argument is passed. Creates a tuple if a
passed as argument
count() Returns the number of times the given element appears in the tuple
index() Returns the index of the first occurance of a given element in the tuple
Takes elements in the tuple and returns a new sorted list. It should be noted that,
sorted()
sorted() does not make any change to the original tuple
min() Returns minimum smallest element of the tuple
max() Returns maximum or largest element of the tuple
sum() Returns sum of the elements of the tuple
12
Page
D0CTIONARY
Dictionary is an unordered collection of data values that store the key : value pair instead of
single value as an element . Keys of adictionary must be unique and of immutable data types
such as strings, tuples etc. Dictionaries are also called mappings or hashes or associative
arrays
Creating a Dictionary
Tocreate a dictionary in Python, key value pair is used
Dictionary is list in curly brackets, inside these curly brackets,keys and values are declared.
Syntax dictionary_name = { keyl:valuel. kev2: value2.. Each key is separated from its
value by a colon (:) while each element is separated by commas
>>> Employees ={"Abhi " : " Manger " " Manish ""Project Manager", " Aasha ":"
Analyst ". " Deepak" :" Programmer "," Ishika ":" Tester "}
Accessing elements from a Dictionary
Syntax: dictionary_name[keys]
>>> Employees[' Aasha ]
'Analyst
Traversing a Dictionary
1. Iterate through all keys 2. Iterate through allvalues
>>>for iin Employees: >>> for i in Employees:
print(i) print(Employees[i)
Output:
Output: Manger
Abhi
Manish Project Manager
Aasha Analyst
Programmer
Deepak Tester
Ishika
3. Iterate through key and values 4. Iterate through key and values simultaneously
>>> for iin Employees: >>> for a,b in Employees. items(0:
print(i, ": ", Employees[i1) print("Key = ".a," and respective value =",b)
Output: Output:
Abhi : Manger Key = Abhi and respective value = Manger
Manish : Project Manager Key = Manish and respective value = Project Manager
Aasha : Analyst Key = Aasha and respective value = Analyst
Deepak : Programmer Key =Deepak and respective value =Programmer
Ishika :Tester Key = Ishika and respective value = Tester
Adding elements to a Dictionary
Syntax: dictionary_name[new key]=value
>>> Employees['Neha'] = "HR"
>>> Employees
Abhi ':" Manger,' Manish ':'Project Manager"," Aasha ':" Analyst', ' Deepak ':"
Programmer,'Ishika ': Tester Neha': 'HR'}
Updating elements in a Dictionary
Syntax: dictionary_name[existing key] =value
>>> Employees['Neha'] ="Progammer "
>>> Employees
(Abhi':"Manger",'Manish ':'Project Manager',' Aasha':'Analyst ','Deepak ': "
Programmer', "Ishika':"Tester', Neha':'Progammer'}
Membership operators in Dictionary
Two membership operators are in and not in. The membership operator inchecks ifthe key is
Page13 present in the dictionary
>>>" Ishika "in Employees >>>'Analyst 'not in Employees
True True
BUILT IN DÊCTIONARY METHODS
Metho Description
len() Returns the length or number of key: value pairs of the dictionary
dict() Creates a dictionary from a sequence of key-value pairs
Returns a list of keys inthe dictionary
keys) Returns a list of values in the dictionary
values()
items() Returns a list of tuples(key - value) pair
as the argument
Returnsthe value correspondingto the key passedreturn
get() None
will
Ifthe key is not present in the dictionary it passed as the argument to the key
update() appends the key-value pair of the dictionary
value pair of the given dictionary
the dictionary from the memory we
del) Deletes the item withthe given key To delete
write: del Dict name
clear() Deletes or clear allthe items of the dictionary
MIND MAP
Method
DList is an ordered sequence len()
of heterogeneous elements list()
DList is created using [] append)
bracket extend()
Individual character in a list insert()
can be assessed using index count()
Lists are mutable index()
remove()
List Osperations LIST pop)
reverse()
D Concatination Operator ()
sort()
OReplication Operators (*) sorted()
DComparison Operators (= min()
>,<,<=,>=,!5)
Membership Operators (in max)
sum)
& not in
Listsupports slicing
Method
D Dictionary is an unordered
collection of data values that store len()
the key :value pair dict)
OKeys of a dictionary must be keys)
unique and of immutable data types DICTIONARY values()
ODictionary is created using {} items()
bracket
get)
Individual character in a dictionary update)
can be assessed using keys
Membership Operators (in & not in del()
checks ifthe key is present in the clear()
dictionary
Method
OEnclosed by single, double or len)
triple quotes title()
Individual character in a string lower()
can be assessed using index upper()
O Strings are immutable count(str, start, end)
find(str,start, end)
index(str, start, end)
STRING endswith)
startswith)
isalnum()
String Operations islower()
D Concatination Operator isupper()
() isspace)
D Replication Operators istitle)
() Istrip)
DComparison Operators ( rstrip)
=,>,<,<F,>=, strip)
replace(oldstr, newstr)
Membership Operators join)
(in ¬ in partition(0)
String supports slicing split)
QUESTIONS:
IMARK QUESTIONS
1. What will be the output of the following set of commands
>>> str ="hello"
>>> str[:2]
a. lo b. he c. llo d. el
2. Which type of object is given below
>>>L= 1,23,"hello", I
a. list b. dictionary c. array d. tuple
Page15 3. Which operator tells whether an element is present in a sequence or not
a. exist b. in c. into d. inside