Python
Sequence - List
Fill in the blanks
1.List is Mutable
2.Tuble is Immutable
3.List index starts with 0
4.List Bracket [] square bracket
5.Tuple bracket ()
6. list = ["hai" , [4,3,96],['p','y','t',’h’,'o','n']] .list[2][2] = t
7.a=[‘h’,’a’,’p’,’p’,’y’]. a[-3]= p
8.b=[‘w’,’e’,’l’,’c’,’o’,’m’,’e’]. b[-4:6]= com
9.print([‘python’]*3)= [‘python’,’python’,’python’]
10.x=[‘p’,’r’,’o’,’b’,’l’,’e’,’m’].del x[1:5] = [‘p’,’e’,’m’]
11.y=[‘w’,’e’,’l’,’c’,’o’,’m’,’e’].print(y.pop()) =e
12. a=[5,1,9,4,3].print(a.sort())= [1,3,4,5,9]
13.z=[3,1,9,5,9,2].print(z.count(9))= 2
14.b=[5,7,3].print(b.append(2))= [5,7,3,2]
15. a=[2,1,3,8].print(b.len())= 4
16. a=[2,1,3,8].print(b.max())= 8
17. a=[2,1,3,8].print(b.min())= 1
18. a=[2,1,3,8].print(b.sum())= 14
19. n = [2,4,6,8]. n[0]=1.print(n)= [1,4,6,8]
20.a=[3,7,8].b=[1,4,9].print(a+b) = [3,7,8,1,4,9]
Answer the following Question
(4 marks)
1.Write a list built-in function.
#empty list 'a'
>>>a=[]
#all() function return true if all
elements are true or list is empty
>>>all(a)
True
>>>a.append(3)
>>>a.appened(4)
>>>a
[3,4]
>>>all(a)
True
>>>a.append(0)
#return false because one zero
element added
>>>all(a)
false
#any() return true if any element of
a list is true
#if list is empty return false
>>>a
[3,4,0]
>>>any(a)
True
>>>b=[]
>>any(b)
False
#example len() to count no of element
in the list
>>>len(a)
3
>>>max(a)
4
>>>min(a)
0
#sorted return a new sorted list(does
not sort the list itself)
>>>sorted (a)
[0,3,4]
#list remain unchanged
>>>d.sorted(a)
>>>d
[0,3,4]
>>>sum(a)
7
2.Write a list Methods.
list1=[34,56,12,56,78,0,6,7,12]
print(list1.index(12))
print(list1.count(12))
list1.sort()
print(list1)
list1.reverse()
print(list1)
OUTPUT
2
2
[0,6,7,12,12,34,56,56,78]
[78,56,56,34,12,12,7,6,0]
3.Write a list change or add element and delete or remove element in List.
HOW TO CHANGE OR ADD
ELEMENTS TO A LIST ?
num = [2,4,6,8]
#change the 1st item
num[0]=1
print(num)
#output: [1,4,6,8]
#change 2nd to 4th items
num[1:4] = [3,5,7]
print(num)
#Output: [1,3,5,7]
HOW TO DELETE OR REMOVE ELEMENTS FROM
A LIST :
we can delete one or more items using
del keyword.
list1=['p','r','o','b','l','e','m']
del list1[2]
print(list1)
Output :
['p','r','b','l','e','m']
del list1[1:5]
print(list1)
Output: ['p','m']
print(list1)
output
['p','r','b','l','e','m']
['p','m']
traceback (most recent call last):
file"c:/python33/ss.py",line
17 , in<module>
print(list 1)
list1 = ['p','r','o','b','l','e','m']
list1.remove('p')
print(list1)
print(list1.pop(1))
print(list1)
print(list1.pop())
print(list1)
list1.clear()
print(list1)
output
['r','o','b','l','e','m']
o
['r','b','l','e','m']
m
['r','b','l','e']
[]
>>>list1 =
['p','r','o','b','l','e','m']
>>>list1[2:3] =[]
>>>list1
['p','r','b','l','e','m']
>>>list1[2:5]=[]
>>>list1
['p','r','m']
No comments:
Post a Comment