You are on page 1of 9

Unit III Unit IV

Strings List Tuple Dictionary


Definition: Definition: Definition: Definition:
A string is a sequence of zero or more A list is a comma-separated sequence of A tuple is comma-separated sequence of values of Dictionary is an unordered collection of items with
values enclosed within single or values of any type enclosed within square [] any type enclosed with or without parentheses (). key: value pair. In a dictionary, items can be of any
double quotes. String is immutable. brackets. List is mutable. Tuple is immutable type. Dictionary is mutable.
Example: s='WELCOME' Example: Example: Example:
L=[10,True,’Hello,3.14] t=(10,True,’Hello’,3.14) d={1:”Hi”,2:”Hello”}

Creation: Creation: Creation: Creation:


1. Strings can be created by placing 1. List can be created by placing the values 1.Tuple can be created by placing the values with or 1. Dictionary can be created by placing the key:value
the values within single or double within square brackets[] without paranthesis() pairs within curly brackets{}
quotes. Syntax: Syntax: Syntax:
Syntax: listname=[values] tuplename=(values) dictionaryname={key:value}
stringname=”values” Example: or Example:
Example: L=[10,True,’Hello,3.14] tuplename=values d={1:”Hi”,2:”Hello”}
s=”Hello” 2.Lists can be created using list() function. Example: 2. Dictionary can also be created by using dict()
2. Strings can be created by str() Empty list is created t=(10,True,’Hello’,3.14) function. Empty dictionary is created.
function. Empty string is created Syntax: 2.Tuple can be created using tuple() function Syntax:
Syntax: listname=list() Syntax: dictionaryname=dict()
stringname=str() Example: tuplename=tuple() Example:
Example: >>>l=list() Example: >>>d=dict()
>>>s=str() >>>print(l) >>>t=tuple() >>>print(d)
>>>print(s) [] >>>print(t) {}
'' ()
3. Creation of tuple with single element
Example: t=1,

Accessing Elements Accessing Elements Accessing Elements Accessing Elements


String can be accessed by using index List can be accessed by using index Tuple can be accessed by using index Dictionary elements can be accessed by using key or
Syntax: Syntax: Syntax: get() function.
stringname[index] listname[index] tuplename[index] Syntax:
Example: Example: Example: dictionaryname[key]
>>>s=”Hello” >>>L=[10,20,30] >>>t=(10,20,30) Or
>>>print(s[0]) >>>print(L[1]) >>>print(t[2]) dictionaryname.get(key)
'H’ 20 30 Example:
>>>d={1:20,2:40}
>>>print(d[2])
40
Strings List Tuple Dictionary
Assigning Values Assigning Values Assigning Values Assigning Values
Values cannot be assigned after Values can be assigned using index Values cannot be assigned after creation because Values can be assigned using key
creation because string is immutable. Example: tuple is immutable. Example:
>>>l=[10,20,30] >>>d={1:20,2:40}
>>>l[3]=40 >>>d[3]=70
>>>print(l) >>>print(d)
[10,20,30,40] {1:20,2:40,3:70}
String Slices List Slices Tuple Slices -
A segment(part) of a string is called a A segment(part) of a list is called a slice. A segment(part) of a tuple is called a slice.
slice. The operator [m:n] returns the part of the The operator [m:n] returns the part of the string
The operator [m:n] returns the part of string from the “m-th” character to the “n-1- from the “m-th” character to the “n-1-th” character.
the string from the “m-th” character to th” character. Syntax:
the “n-1-th” character. Syntax: Tuplename(startindex : endindex)
Syntax: Listname[startindex : endindex] Example:
stringname[startindex : endindex] Example: >>>t= (1,2,3,4,5)
Example: >>>l= [1,2,3,4,5] >>> t[1:3]
>>>s=”Hello Python” >>> l[1:3] (2,3)
>>>print(s[1:3] ) [2,3]
el

Operations Operations Operations -


1. Concatentation: 1. Concatentation: 1. Concatentation:
+ operator concatenates the given The + operator concatenates lists The + operator concatenates tuples
strings >>> a = [1, 2, 3] >>> a = (1, 2, 3)
>>> a = “Hello” >>> b = [4, 5, 6] >>> b = (4, 5, 6)
>>> b =”World” >>> c = a + b >>> c = a + b
>>> c = a + b >>>print(c) >>>print(c)
>>>print(c) [1, 2, 3, 4, 5, 6] (1, 2, 3, 4, 5, 6)
“Hello World” 2. Repetition: 2. Repetition:
2. Repetition: The * operator repeats a list a given number The * operator repeats a list a given number of
The * operator repeats a list a given of times: times:
number of times. >>> [1,2] * 4 >>> (1,2) * 4
>>>’H’ * 4 [1,2,1,2,1,2,1,2] (1,2,1,2,1,2,1,2)
‘HHHH’

Immutability Mutability Immutability Mutability


Strings are immutable. It means that List are mutable. Values can be changed. Tuples are immutable. It means that modification is Dictionary is mutable.
modification is not allowed in strings. Example: not allowed in tuples Keys are immutable but values can be changed.
Example: >>>l=[10,20,30] Example: Example:
>>>s=”Hello” >>>l[1]=40 >>>t=(10,20,30) >>>d={1:20,2:40}
>>>s[0]=’J’ >>>print(l) >>>t[0]=40 >>>d[2]=50
Error will be displayed [40,20,30] Error will be displayed >>>print(d)
{1:20,2:50}
Strings List Tuple Dictionary
Deletion Deletion Deletion Deletion
del 1. pop() del del
-to remove the entire string. deletes and returns the last element. -to remove the entire tuple. Individual elements - to remove individual items or the entire dictionary
Syntax: pop(index) cannot be deleted. itself.
del stringname deletes and returns the given element Syntax: Syntax:
Example: Syntax: del tuplename del dictionaryname[key]
>>>s=”Hello” listname.pop() Example: del dictionaryname
>>>del s listname.pop(index) >>>t=(10,20,30) Example:
Example: >>>del t >>>d = {1: 'apple', 2: 'ball'}
>>> l = [10,20,30] >>> del d[1]
>>> x = l.pop(1) >>> d
>>> print(l) {1: 'apple'}
[10,30] 2.pop()
>>>print( x) - can remove a particular item in a dictionary.
20 Syntax:
2. del : dictionaryname.pop(key)
-delete the element at the given index. Example:
Syntax: >>>d = {1: 'apple', 2: 'ball'}
del listname[index] >>>d.pop(1)
Example: 'apple'
>>> l = [10,20,30] 3.popitem()
>>>del l[2] - can be used to remove last element in dictionary.
>>> l Syntax:
[10,20] dictionaryname.popitem()
3.remove(): Example:
remove the given element when the index >>>d = {1: 'apple', 2: 'ball'}
is not known >>>d.popitem()
Syntax: (2: 'ball')
listname.remove(element) 4.clear()
Example: - All the items can be removed at once.
>>>l = [10,20,30] Syntax:
>>>l.remove(20) dictionaryname.clear()
>>> l Example
[10,30] >>> d = {1: 'apple', 2: 'ball'}
>>> d.clear()
>>> d
{}
Strings List Tuple Dictionary
String Functions and Methods List Methods Tuple Methods Dictionary Operations and Methods
Len() Len() Len() Len()
-Returns the length of the given string -Returns the length of the given list -Returns the length of the given list -Returns the length of the given string
Syntax: Syntax: Syntax: Syntax:
len(stringname) len(listname) len(tuplename) len(dictionaryname)
Example: Example: Example: Example:
>>>s="Hello" >>>l=[10,20,30] >>>t=(10,20,30) >>>d={1:20,2:30}
>>>print(len(s)) >>>print(len(l)) >>>print(len(t)) >>>print(len(d))
5 3 3 2

count() count() count() -


-Returns the number of occurrences of - returns the number of occurrences of the - returns the number of occurrences of the given
the given substring. given element. element
Syntax: Syntax Syntax
stringname.count(substring) listname.count(element) tuplename.count(element)
Example: Example Example
>>>s="hello" >>> l= [30,20,10,50,30] >>> t= (30,20,10,50,30)
>>>s.count("l") >>>l.count(30) >>>t.count(30)
2 2 2

index() - index() dict()


-Returns Index of Substring -Returns Index of Substring - Creates a new dictionary.
Syntax: Syntax: Syntax:
stringname.index(substring) stringname.index(element) dictionaryname=dict()
Example: Example: Example
>>> s="Hello" >>>t=(10,20,30) >>>d=dict()
>>> print(s.index('e')) >>> print(t.index(30)) >>>print(d)
1 2 {}
dict(sequence)
- Creates a new dictionary with key values and their
associated values from sequence.
Syntax:
dictionaryname=dict(sequence)
Example:
>>>t = {1:'d',4: 'c', 6:'e', 7:'b',2: 'a'}
>>> d=dict(t)
>>>print(d)
{1:'d',4: 'c', 6:'e', 7:'b',2: 'a'}
Strings List Tuple Dictionary
lower() append() get(key)
- Returns a string with all lowercase - adds a new element to the end of a list. - returns the element associated with the given
letters. Syntax: key.
Syntax: listname.append(element) Syntax:
stringname.lower() Example: dictionary.get(key)
Example: >>> l= [10,20,30] Example:
>>>s="Hello" >>> l.append(40) >>> d = {1: 'apple', 2: 'ball'}
>>>print(s.lower()) >>>print(l) >>> print(d.get(2))
Hello [10,20,30,40] ball
upper() Extend() items()
-Returns a string with all uppercase - takes a list as an argument and appends all - Returns a list of items(key:value)tuple pairs in the
letters. of the elements. dictionary.
Syntax: Syntax: Syntax:
stringname.upper() listname1.extend(listname2) dictionaryname.items()
Example: Example: Example:
>>>s="hello" >>> l1 = [10,20,30] >>>d = {1:'f',4: 'c', 6:'e', 7:'b',2: 'a'}
>>>print(s.upper()) >>> l2 = [40,50] >>> print(d.items())
HELLO >>> l1.extend(l2) dict_items([(1, 'd'), (4, 'c'), (6, 'e'), (7, 'b'), (2, 'a')])
>>> print(l1)
[10,20,30,40,50]

islower() Sort() sorted(dictionary)


-Returns True if all alphabets in the - arranges the elements of the list in - returns the sorted list of keys in the dictionary.
given string are in Lowercase. ascending order. Syntax:
Otherwise returns False Syntax: sorted(dictionaryname)
Syntax: listname.sort() Example
stringname.islower() Example: >>>d = {1:'f',4: 'c', 6:'e', 7:'b',2: 'a'}
Example: >>> l= [30,20,10,50] >>>print(sorted(d))
>>> s="hello" >>> l.sort() [1, 2, 4, 6, 7]
>>>print(s.islower()) >>>print(l) key in d
True [10,20,30,40,50] - used to check whether the given key is found in
isupper() reverse() dictionary.
-Returns True if all alphabets in the - used to reverse the entire list. - If it is found, returns True . Otherwise, returns False
given string are inUppercase. Syntax: Syntax:
Otherwise returns False listname.reverse() key in dictionaryname
Syntax: Example: Example:
stringname.isupper() >>> l= [30,20,10,50] >>>d= {1:'f',4: 'c', 6:'e', 7:'b',2: 'a'}
Example: >>>l.reverse() >>>print(4 in d)
>>> s="hello" [50,10,20,30] True
>>>print(s.isupper())
False
Strings List Tuple Dictionary
find() pop() - pop(key)
Returns the index of given substring. - removes and returns the last element in the - Return and remove the item associated with the
If the given substring is not found, list. given key in a dictionary.
then it returns -1. Syntax: Syntax:
Syntax: listname.pop() dictionaryname.pop(key)
stringname.find(substring) Example: Example:
Example: >>> l= [30,20,10,50,30] >>>d = {1: 'apple', 2: 'ball', 3:'box'}
>>>s=”Hello” >>> l.pop() >>>d.pop(1)
>>>s.find(‘lo’) 30 'apple'
3 pop(index) Popitem()
replace() - removes and returns the element at given - can be used to remove and return last item.
-Returns a copy of the string where old index in the list. Syntax:
substring is replaced with the new Syntax: dictionaryname.popitem()
substring. The original string is listname.pop(index) Example:
unchanged. Example: >>>d = {1: 'apple', 2: 'ball', 3:'box'}
Syntax: >>> l= [30,20,10,50] >>>d.popitem()
stringname.replace(oldstring,newstr >>> l.pop(2) (3, 'box')
ing) 10 clear()
Example: Remove() - All the items in the dictionary can be removed at
>>>print(s.replace("hello","world")) - used to remove the given element. once.
'world' Syntax: Syntax:
>>> print(s) listname.remove(element) dictionaryname.clear()
Hello Example: Example
>>> l= [30,20,10,50] >>> d = {1: 'apple', 2: 'ball', 3:'box'}
>>> l.remove(10) >>> d.clear()
>>> print(l) >>> d
[30,20,50] {}
insert() keys()
- used to insert the given element in the - Returns a list of keys in dictionary.
given position. Syntax:
Syntax: dictionaryname.keys()
listname.insert(index,element) Example:
Example: >>>d = {1:'f',4: 'c', 6:'e', 7:'b',2: 'a'}
>>> l= [30,20,10,50,30] >>> print(d.keys())
>>> l.insert(4,60) dict_keys([1, 4, 6, 7, 2])
>>>print(l) values()
[30, 20, 10, 50, 60, 30] - Returns the lsit of values in the dictionary.
Syntax:
dictionaryname.values()
Example:
>>>d= {1:'f',4: 'c', 6:'e', 7:'b',2: 'a'}
>>> print(d.values())
dict_values(['f', 'c', 'e', 'b', 'a'])
UNIT III
Types of Conditional Statements Types of Iteration Statements Loop Control Statements
1. Conditional(if) 1. state 1. break
2. Alternative(if-else) 2. while 2. continue
3. Chained Conditional(if..elif..else) 3. for 3. pass
4. Nested Conditionals 4. break
5. continue
6.pass
Types of Conditional Statements(16 mark)
CHAINED CONDITIONAL
CONDITIONAL (IF) ALTERNATIVE (IF-ELSE) (IF-ELIF-ELSE) NESTED CONDITIONALS
Conditional statements give us the A second form of the if statement is “alternative If there are more than two possibilities, Conditionals can be nested within
ability to check conditions. execution”. more than two branches is needed, so another.
If booleanexpression is true,statements If booleanexpression is true,statements-1 will be chained conditional is used. elif is an
will be executed. If not, nothing executed or statements-2 will be executed abbreviation of “else if”.
happens. There is no limit on the number of elif
statements.
Syntax: Syntax Syntax Syntax
if booleanexpression: if booleanexpression: if booleanexpression1: if booleanexpression1:
statements Statements-1 Statements-1 Statements-1
else: elif booleanexpression2: else:
Statements-2 Statements-2 if booleanexpression2:
else: Statements-2
Statements-3 else:
Statements-3
Program Program: Program: Program:
x=int(input(“Enter a number”)) year=int(input(“Enter a year”)) x=int(input(“Enter the value of x”) x=int(input(“Enter the value of x”)
if(x>0): if(year%4)= =0: y=int(input(“Enter the value of y”) y=int(input(“Enter the value of y”)
print(“Positive Number”) print(“Leap Year”) if x < y: if x == y:
else: print(“x is less than y”) print(“x and y are equal”)
print(“Not a Leap Year”) elif x > y: else:
print(“x is greater than y”) if x < y:
else: print(“x is less than y”)
print(“x and y are equal”) else:
print(“x is greater than y”)
Output: Output: Output: Output:
Enter a number Enter a year Enter the value of x Enter the value of x
3 2016 5 5
Positive Number Leap Year Enter the value of y Enter the value of y
4 4
x is greater than y x is greater than y
ITERATION STATEMENTS (Each 4 mark)
An iteration statement allows a code block to be repeated a certain number of times.
While For Break Continue
A while loop statement repeatedly For statement iterates over the items of any sequence in The break statement breaks out of the The continue statement causes the loop
executes a target statement until the the order that they appear in the sequence. innermost enclosing for or while loop. to skip the rest of the body and
condition is true. The built-in function range() is used to iterate over a The break statement breaks the loop immediately retest its condition before
Here, statement(s) may be a single sequence of numbers. statement and transfers flow of reiterating.
statement or a block of statements. execution to the statement immediately
following the loop.

Syntax: Syntax: Syntax: Syntax:


while expression: 1) for <variable> in <sequence>: break continue
statement(s) <statements>
else:
<statements>
2) for variablename in range(startvalue, endvalue):
statement(s)
Program: Example 1: Working of break statement: Working of continue statement:
count = 0 >>> languages = ["C", "C++", "Perl", "Python"] for variablename in sequence: for variablename in sequence:
while (count < 9): >>> for x in languages: if condition: if condition:
print ("The count is:", count) print(x) break continue
count = count + 1 Output statement(s) statement(s)
print ("Good bye!") C Program: Program:
Output: C++ for val in “string”: for val in “string”:
The count is: 0 Perl if val==”i”: if val==”i”:
The count is: 1 Python break continue
The count is: 2 Example2: print(val) print(val)
The count is: 3 >>>for i in range(5, 10): print(“End”) print(“End”)
The count is: 4 print(i) Output: Output:
The count is: 5 Output s s
The count is: 6 5 t t
The count is: 7 6 r r
The count is: 8 7 End n
Good bye! 8 g
9 End
State Pass
It is possible to have more than one assignment for the same variable. The pass statement do nothing.
The value which is assigned at the last is given to the variable. It can be used when a statement is required syntactically but the program
Example requires no action.
x=5 Syntax:
y=3 pass
x=4 Program:
print(x) sequence={'p','a','s','s'}
Output: for val in sequence:
4 pass
3 Output:
No output will be displayed.

You might also like