Notes - Strings,List,Tuple,Dictionary
Notes - Strings,List,Tuple,Dictionary
LISTS
• Lists are sequences that store a list of values of any datatype.
• Lists are Mutable i.e we can change the elements of a list in place
• It is defined inside square brackets [ ]
• Ex:
[] empty list
[5,10,15] integer list
[‘aba’,1,3.2,’aa’,32] mixed list
[ 10,20,[‘a’,’b’,’c’],30,40] Nested list (list
inside a list)
CREATING A LIST
1. L1=[1,2,3,4,5,6,7,8]
2. L2 = list( ) or L2 = [ ] #creates an empty list
3. L3= list(‘Goodday’) will create a list L3=[‘G’,’o’,’o’,’d’,’d’,’a’,’y’]
4. L4= list(input(“Enter list elements:”))
Enter list items: 98765 will create a list L4=[‘9’,’8’,’7’,’6’,’5’]
(or) Enter list items: aeiou will create a list L4=[‘a’,’e’,’i’,’o’,’u’]
Here everything is taken as a string.
5. L5= eval(input(“Enter the list items:”))
Enter the list items: [11,12,13,14,55] # we should enter the elements
# inside the square brackets.
eval( ) function
• Used to evaluate and return the result of an expression given as string.
Ex:
>>a= eval(‘30’+’45’)
>>print(a) - will give 75 as result
• It will interpret the values given as the intended types
Ex:
x = eval(input(“Enter a value”))
if (i) x is given 10 it is taken as an integer
(ii) x is given 34.2 it is taken as float
(iii) x is given [12,13,14] it is taken as list etc
Indexing in list
Similar to strings, has both forward and backward indexing.
list1= [11,21,34,41,58,60,73,89,94]
0 1 2 3 4 5 6 7 8
11 21 34 41 58 60 73 89 94
-9 -8 -7 -6 -5 -4 -3 -2 -1
Traversing in a list
Traversing a list means accessing and processing each element in the
list. That’s why traversal sometimes call as looping over a sequence.
Ex:
(i) S= [ ‘c’,’o’,’m’,p’,’a’,’r’,’e’]
for x in S:
print(x,end=” “) #will print the result as c o m p a r e
here x will be assigned directly to the list elements one at a time.
(ii) If we need the indexes of the elements to access them ,then we the
range
function.
for x in range(len(S)):
print (x,S[x]) # will print the same result as c o m p a r e
List Operations
(i) Concatenation (+) : Creates a new list by joining two lists
Ex: a= [1,3,5] b = [2,4,6]
c=a+b
will create list c =[1,2,3,4,5,6]
but both the operand should be of list types. We cannot add a list to a
number, complex number or a string.
(ii) Replication Operator (*) : It takes a list and replicate it the specified
number
of times.
Ex: lst1 = [2,3,4]
>>lst1*4
will give result [2,3,4,2,3,4,2,3,4]
(iii) Membership Operators :
in : returns True if a element is present in the list,
otherwise returns False.
not in : returns True if a element is not present in the list ,
otherwise returns False.
Ex: 2 in [11,2,3,4] will give True
5 not in [55,65,5,75,85] will give False
nos=[10,20,30,40,50]
>>nos[3: ] = “54321”
>>nos
[10, 20, 30, '5', '4', '3', '2', '1']
Operations on a List
(i) Adding elements to a list
The append() method is used to add a single element to the
end of the list.
Syntax: listobject.append(item)
L=[12,43,56,89]
>>L.append(32)
>>L
[12,43,56,89,32]
(ii) Updating elements in a list
>> list1=[1,2,3,’aa’,5]
>>list1[3] = 4
>>list1
>>[1,2,3,4,5]
(ii) Deleting elements from a list
a. del statement
• The del statement can be used to remove an individual item, or
remove all items identified by a slice.
• It takes the index of the elements to delete it.
A=[10,20,30,40,50,60,70,80,90,100]
>>del A[4]
>>A
[10,20,30,40,60,70,80,90,100], # 50 is the element present in index 4
A=[10,20,30,40,50,60,70,80,90,100]
>>del A[3:6]
>>A
[10,20,30,70,80,90,100]
b. pop() method
It removes an individual element and returns it.
Syntax: lstobject .pop(index)
Ex:
L1=[11,23,45,66,88,46,89]
>>L1.pop(4)
88
>>L1
[11,23,45,66,46,89]
This method is useful when we want to restore the element that is
been deleted for later use
Ex: x1 = L1.pop(2) #element 45 will be stored in x1
Difference between del statement and pop()
Del statement Pop() method
It can remove a single element or a list The pop() method removes only a single
slice from a list element
It does not return the deleted element, It returns the deleted element. So we
so item once deleted cannot be can assign it to a variable and retrieve
retrieved it later if needed.
So, any changes made to x will also be reflected to y and vice versa
Ex: x[3] = 72
>>x
[10,20,34,72,78]
>>y
[10,20,34,72,78]
Method 2:
x = [1,2,3,4,5]
>>y = list(x)
>>x[2]=’A’
>>x
[1,2,’A’,4,5]
>>y
[1,2,3,4,5]
Here two independent copies of list are made. So changes to one list will not
affect the other.
10 20 ‘A’ 56 78
10 20 34 56 78
LIST FUNCTIONS & METHODS
METHOD EXPLANATION EXAMPLE RETUR
N
(YES/N
O)
index() • Returns the first Ex 1: Yes
method index of the first A1=[13,14,15,16,17,16,18]
matched item from >>A1.index[16]
the list 3
Syntax:
listobject.index(item) Ex 2:
• If the element is not >> C = A1.index[14]
found then it raises >>C
an exception - value 1
error
TUPLES
• Tuples are sequences that are used to store values of any type.
• Tuples are Immutable i.e we cannot change the elements of tuple in
place
• They are depicted through Parentheses Ex: (1,2,3,4)
• Creating a Tuple
Empty Tuple T1=tuple() or T1=( )
Single element tuple T2=(4, ) or T2 =4,
Long Tuples T3=(2,7,4,6,7,33,2)
Nested Tuples T4= (22,44,66,1,(3,4,5),5)
Creating tuple from a T5=tuple(“hello”)
Sting >>T5
(‘h’,’e’,’l’,’l’,’o’)
Creating a tuple from a L=[2,3,4,5,6]
list T6=tuple(L)
>>T6
(2,3,4,5,6)
Creating a tuple during T7=tuple(input(“Enter tuple items:”))
runtime >>Enter tuple items: 34567
>>T7
(‘3’,’4’,’5’,’6’,’7’) #created as string type
(or)
T7=eval(input(“Enter tuple items:”))
>>Enter tuple items: (3,4,’a’,(1,2,),4)
>>T7
(3,4,’a’,(1,2,),4)
2. Indexing in tuple
Similar to strings and list , has both forward and backward indexing.
tup1= (11,21,34,41,58,60,73,89,94)
0 1 2 3 4 5 6 7 8
11 21 34 41 58 60 73 89 94
-9 -8 -7 -6 -5 -4 -3 -2 -1
3. Traversing in a tuple
Traversing in a tuple means accessing and processing each element in
the tuple.
Ex:
(i) M= (‘hello’,1,2,3)
for x in M:
print(x,end=” “) #will print the result as ‘hello’ 1 2 3
here x will be assigned directly to the tuple elements one at a time.
(ii) If we need the indexes of the elements to access them ,then we the
range
function.
for y in range(len(M)):
print (M[y]) #will print the result as ‘hello’ 1 2 3
4.Tuple Operations
(i) Joining Tuples : Creates a new tuple by joining two or more tuples.
Ex: a= (1,2,3) b = (4,5,3) c=(7,8,9)
d=a+b+c
will create a tuple d =(1,2,3,3,4,5,7,8,9)
but both the operand should be of tuple types. We cannot add a tuple to a
number, complex number, string or list.
(ii) Replication Operator (*) : It takes a tuple and replicate it the specified
number of times.
Ex: tup1 = (5,7,8)
>>tup1*3
will give result (5,7,8,5,7,8,5,7,8)
(iii) Membership Operators :
in : returns True if a element is present in the tuple,
otherwise returns False.
not in : returns True if a element is not present in the tuple ,
otherwise returns False.
Ex: 5 in (11,2,3,4) will give False
(iv) Comparing Tuples
• To compare two tuples we use the comparison operators <,>,==,!=
• It produces result True or False by comparing corresponding elements, if
corresponding elements are equal , it goes to the next element, and so
on, until it finds elements that differ.
A=(1,2,3) B=(1,2,3) True Both the list are equal
A==B
A=(1,2,3) B=(‘1’,’2’,3) False One tuple contains
A==B integers and another
tuple contains strings
C=(2.0,3.0) D=(2.0,3.7) False First element is same but
C>D the last element of the
second list is greater
than the first list .
5. Unpacking Tuples
• Creating a tuple from a set of values is called packing
• Creating individual values from a tuple’s elements is called Unpacking
Syntax:
<var1>,<var2>,<var3>=tuple
The number of variables in the left side of assignment must match the
number of elements in the tuple.
Ex1: T=(1,’hi,3,’hello’)
a,b,c,d = T
>>print(a,b,c,d)
• ‘hi’ 3 ‘hello’
Ex 2: L1=[10,20,30]
T=(200,300)
L1[0],L1[2] = T
>>L1
[200,20,300] #the first and the third list item is replaced with the
#elements of the tuple
6. Deleting Tuples
• As tuples are immutable, which means that the individual
elements of a tuple cannot be deleted.
T1=(21,35,42,51,62,78)
>>del T1[2]
• will produce a trace back error message stating that ‘Tuple’ object
does not support deletion.
• But we can delete a complete tuple with del statement.
Syntax: del <tuple_name>
del T1 # will delete the entire tuple object
TUPLE FUNCTIONS & METHODS
METHOD EXPLANATION EXAMPLE RETURN
(YES/NO)
len () • Returns the length of Ex 1: Yes
method the tuple. T1=(2,3,4,5,6,7)
Syntax: len(<tuple>) >>len(T1)
• Take tuple name as 6
argument and returns
an integer.
Nesting Dictionaries :
You can add dictionary as value inside a dictionary. This type of
dictionary known as nested dictionary.
For example:
Visitor ={‘Name’:’Scott’,’Address’:{‘hno’:’11A/B’,’City’:’Kanpur’,
’PinCode’:’208004’},‘Name’:’Peter’,’Address’:{‘hno’:’11B/A’,’City’:’Kanpur’,
’ PinCode’:’208004’}
To print elements of nested dictionary is as :
>>> Visitor['Name'] 'Scott'
>>> Visitor['Address']['City'] # to access nested elements 'Kanpur'
dictionaryName.pop([“Key”])
>>> D1 = {1:10,2:20,3:30,4:40}
>>> D1.pop(2) 1:10,3:20,4:40
Note: if key passed to pop() doesn’t exists then python will raise an exception.
Pop() function allows us to customized the error message displayed by use of
wrong key
>>> d1
{'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'}
>>>d1.pop(‘a’)
>>> d1.pop(‘d‘,’Not found’) Not found
We can check the existence of key in dictionary using “in” and “not in”.
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>> 'a' in alpha
True
>>>’e’ in alpha False
>>>’e’ not in alpha True
⦁ If you pass “value” of dictionary to search using “in” it will return False
>>>’apple’ in alpha False
To search for a value we have to search in
dict.values()
>>>’apple’ in alpha.values()
PRETTY PRINTING
To print dictionary in more readable form we use json module. i.e. import json
and then call the function dumps()
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>>import json
>>> print(json.dumps(alpha,indent=2))
{
"a": "apple",
"c": "cat",
"b": "boy",
"d": "dog"
}
METHODS/FUNCTIONS IN DICTIONARY