100% found this document useful (1 vote)
2K views8 pages

List and Tuple Worksheet Solution

The document contains solutions to various questions related to list manipulation in Python. Some key points: 1) Questions cover list operations like indexing, slicing, sorting, doubling, inserting, removing and modifying elements. 2) The differences between various list methods are explained, such as append vs extend, pop vs remove, sort vs sorted, clear vs del. 3) Examples show how to add/modify elements based on conditions like even/odd indexes, every third element, removing all occurrences of a value. 4) A question demonstrates a menu driven program to add/delete elements from a list by index or value as per user choice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views8 pages

List and Tuple Worksheet Solution

The document contains solutions to various questions related to list manipulation in Python. Some key points: 1) Questions cover list operations like indexing, slicing, sorting, doubling, inserting, removing and modifying elements. 2) The differences between various list methods are explained, such as append vs extend, pop vs remove, sort vs sorted, clear vs del. 3) Examples show how to add/modify elements based on conditions like even/odd indexes, every third element, removing all occurrences of a value. 4) A question demonstrates a menu driven program to add/delete elements from a list by index or value as per user choice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Delhi Public School, Azaad Nagar, Kanpur

Worksheet-List Manipulation
Solution
Q1. Start with the list[8,9,10]. Do the following using list functions
(a) Set the second entry (index 1) to 17
(b) Add 4, 5 and 6 to the end of the list.
(c) Remove the first entry from the list.
(d) Sort the list. e) Double the list. f)Insert 25 at index 3
Ans:
a) list[1]=17
b) list.append(4) list.append(5) list.append(6)
c) list.pop(0)
d) list. sort()
e) list=list*2
f) list. insert(3,25)
Q2. If a is [1, 2, 3], what is the difference (if any) between a*3 and [a, a, a]?
Ans: a*3 will produce [1,2,3,1,2,3,1,2,3], means a list of integers and [a, a, a] will produce [[1,2,3],[1,2,3],[1,2,3]], means list of
lists
Q3.If a is [1, 2, 3], is a *3 equivalent to a + a + a?
Ans: Yes, Both a*3 and a+a+a will produce same result.

Q4.How are lists different from strings when both are sequences?
Ans: Lists are similar to strings in many ways like indexing, slicing, and accessing individual elements but they are different in the
sense that Lists are mutable while strings are immutable.

i. In consecutive locations, strings store the individual characters while list stores the references of its elements.
ii.Strings store single type of elements-all characters while lists can store elements belonging to different types.
Q5.Differentiate between
1. Pop() and remove()
pop() and del remove()
del is a keyword and pop () is a built in method remove () method delete values or object from the list
both deletes values or object from the list using an using value. The remove() method removes the first
index. pop() returns deleted value. matching value from the list.
numbers = [1, 2, 3, 2, 3, 4, 5] numbers = [1, 2, 3, 2, 3, 4, 5]
del numbers[2] numbers. remove(2)
print(numbers) print(numbers)
numbers.pop() print(numbers. remove(1))
print(numbers) print(numbers)
print(numbers.pop(-1))
print(numbers)
OUTPUT OUTPUT
[1, 2, 2, 3, 4, 5] [1, 3, 2, 3, 4, 5]
[1, 2, 2, 3, 4] None # not return any value
4 [3, 2, 3, 4, 5]
[1, 2, 2, 3]
2. Append() and extend()
Append() Extend()
It adds a single item to the end of the list It adds one list at the ends of another list.
my_list = ['python', 'for'] my_list = ['python', 'is']
my_list.append('learning') my_list.extend('easy')
print (my_list) print (my_list)
my_list.append([1,2]) my_list.extend([1,2])
print(my_list) print(my_list)
OUTPUT OUTPUT
['python', 'for', 'learning'] ['python', 'is', 'e', 'a', 's', 'y']
['python', 'for', 'learning', [1, 2]] ['python', 'is', 'e', 'a', 's', 'y', 1, 2]
3. Clear() and del
clear(): clear() method in python is used to empty the entire list. this can be used if someone wants an empty list for any other
purpose.

Eg:
numbers = [1, 2, 3, 2, 3, 4, 5]
print(numbers)
numbers.clear()
print(numbers)
o/p
[1, 2, 3, 2, 3, 4, 5]
[]
3. Sort() and sorted()
Sort() Sorted()
sort() function is very similar to sorted() but unlike sorted() method sorts the given sequence either in
sorted it returns nothing and makes changes to the ascending order or in descending order and always
original sequence. Moreover, sort() is a method of return the a sorted list. This method does not effect the
list class and can only be used with lists. original sequence. sequence list, tuple, string or
dictionary.
numbers = [1, 3, 4, 2] numbers =[1, 3, 4, 2]
numbers. sort() numbers1=sorted(numbers)
print(numbers) print(numbers1)
numbers. sort(reverse=True) numbers={4:'a',1:'b',3:'c'}
print(numbers) numbers1=sorted(numbers, reverse=True)
print(numbers1)
numbers="1265"
numbers1=sorted(numbers, reverse=True)
print(numbers1)
OUTPUT OUTPUT
[1, 2, 3, 4]
[1, 2, 3, 4] [4, 3, 1]
[4, 3, 2, 1] ['6', '5', '2', '1']

Q6.Find the output:


1.L = ['a', 'b', ['cc', 'dd', ['eee', 4.
2.
'fff']], 'g', 'h'] l1=[1,3,5,7,9]
l=[2,6,7]
print(L[2]) print(l1==l1.reverse())
a=l
print(L[2][2]) print(l1)
a.append(20)
print(L[2][2][0]) OUTPUT
print(l)
print(L[0:2]) False
OUTPUT
print(L[-3]) [9, 7, 5, 3, 1]
[2, 6, 7, 20]
OUTPUT
['cc', 'dd', ['eee', 'fff']]
['eee', 'fff'] 3. 5.
eee l=[1,2,7,9] l=[2,3,4,6]
['a', 'b'] a=list(l) l.reverse()
['cc', 'dd', ['eee', 'fff']] print(l)
a[1]=100
_________________________ l.sort(reverse=True)
6.l=[1,2,7,9] print(l) print(l)
del l[0:2] OUTPUT OUTPUT
print(l) [1, 2, 7, 9] [6, 4, 3, 2]
OUTPUT [6, 4, 3, 2]
[7, 9]
7.>>> l=[1,2,3] 8.l=[1,2,7,9] 9.l=[1,2,7,9]
>>> l[3:]="hello" a=l.copy() l.pop()
>>> print(l) a[1]=100 print(l)
>>> l[10:20]=200,300 l.pop(2)
print(l)
>>> print(l) print(l)
>>> l[3:]=100 #error OUTPUT OUTPUT
OUTPUT [1, 2, 7, 9] [1, 2, 7]
[1, 2, 3, 'h', 'e', 'l', 'l', 'o'] [1, 2]
[1, 2, 3, 'h', 'e', 'l', 'l', 'o', 200,
300]
Q7.Add 5 in every even value of a List
Eg: 'Original List', [12, 3, 48, 9, 10, 15, 18, 33, 1, 62]
updated List', [17, 3, 53, 9, 15, 15, 23, 33, 1, 67]
Ans:
l=[12,3,48,9,10,15,18,33,1,62]
for i in range(len(l)):
if l[i]%2==0:
l[i]=l[i]+5
print(l)
Q8-Add 2 in odd index value. L=[2,3,1,4,3,2]
Ans:
l=[2,3,1,4,3,2]
for i in range(len(l)):
if i%2!=0:
l[i]=l[i]+2
print(l)
Q 9. l=[2,3,4,1,5,22,6,9,2,5,8,1,5,10,6] Display sum of every third element of a list
Ans:
l=[2,3,4,1,5,22,6,9,2,5,8,1,5,10,6]
i=sum=0
while i<len(l):
sum=sum+l[i]
i=i+3
print("sum is",sum)
OUTPUT
sum is 19
Q10. Delete all 2 from list l=[1,2,7,2,4,2,5,2]
Ans:
l=[1,2,7,2,4,2,5,2]
i=0
while i<len(l):
if l[i]==2:
l.remove(2)
i=i+1
print(l)
OUTPUT
[1, 7, 4, 5] OR
l=[1,2,2,2,2,2,5,2]
i=0
while i<len(l):
if l[i]==2:
l.remove(2)
i=i-1
i=i+1
print(l)
OUTPUT
[1, 5]
Q11.WAP that displays options for inserting or deleting element from list as per user’s choice to be delete/add by value or index.
Ans:
l=[12,45,89,22,41]
print("List is")
for i in range(len(l)):
print("index:",i,"value:",l[i])
c=""
while True:
print("press1 to add by index no.")
print("press2 to add by value")
print("press3 to delete by index")
print("press4 to delete by value")
ch=int(input("Enter your choice"))
if ch==1:
value=int(input("enter a value"))
i=int(input("Enter index no. from 0-4 to add value"))
l.insert(i,value)
print("value added\nupdated list is")
print(l)
elif ch==2:
v=int(input("Enter a value to be added"))
l.append(v)
print("value added\nupdated list is")
print(l)
elif ch==3:
i=int(input("Enter index no. from 0-4 to be deleted"))
if i>=0 and i<=4:
l.pop(i)
print("value deleted\nupdated list is")
print(l)
else:
print("wrong index no.")
elif ch==4:
v=int(input("Enter a value to be deleted"))
l.remove(v)
print("value deleted\nupdated list is")
print(l)
else:
print("wrong choice")
c=input("Do you want to continue")
if c=='n' or c=="no":
break
OUTPUT
List is
index: 0 value: 12
index: 1 value: 45
index: 2 value: 89
index: 3 value: 22
index: 4 value: 41
press1 to add by index no.
press2 to add by value
press3 to delete by index
press4 to delete by value
Enter your choice1
enter a value3
Enter index no. from 0-4 to add value62
value added
updated list is
[12, 45, 89, 22, 41, 3]
Q12. WAP to find the frequencies of all elements of a list. Also ,print the list of unique elements in the given list.
Ans:
c={}
b=[]
a=[4,4,4,2,8,3,2,1,5,4,4,4]
for i in range(0,8):
if(a[i]not in b):
b.append(a[i])
print("Actual List",a)
print("Unique Elements of a List",b)
for i in b:
k=0
for j in range(0,len(a)):
if(i==a[j]):
k=k+1
c[i]=k
for key in c:
print(key,"frequency is=",c[key])
OUTPUT
Actual List [4, 4, 4, 2, 8, 3, 2, 1, 5, 4, 4, 4]
Unique Elements of a List [4, 2, 8, 3, 1]
4 frequency is= 6
2 frequency is= 2
8 frequency is= 1
3 frequency is= 1
1 frequency is= 1
Worksheet-Tuple
Q1. How can you add an single element to a tuple?
Ans A single value in() is treated as single value not as tuple . That is exressions (3) and (‘a) are integer and string But (3,) and
(‘a’,) are example of tuple with single element.
T=(10,5,6,7)
T+(3,)
print T Output (10,5,6,7,3)

Q2.Find out the output generated by following code fragments:


a) t1=(1,2,3,4,5) #created tuple (b) (a, b, c) = (1,2,3) (c) (a, b, c, d) = (1,2,3)
(d) a, b, c, d = (1,2,3) (e) a, b, c, d, e = (p, q, r, s, t) = t1
Ans: b)This will assign 1 to a, 2 to b and 3 to c.
c)ValueError: not enough values to unpack (expected 4, got 3)
d)ValueError: not enough values to unpack (expected 4, got 3)
e)If tuple t1 has 5 values then this will assign first value of t1 in to a and p , next value to b and q and so on.

Q.3Predict the output –


l=[2,3,4,6] Q5.x = ("apple", "banana", "cherry")
t=tuple(l) y = list(x)
print(t) y[1] = "kiwi"
print(tuple(l)) x = tuple(y)
t=tuple(input("enter 3 print(x)
elements")) OUTPUT
print(t) ('apple', 'kiwi', 'cherry')
OUTPUT
(2, 3, 4, 6)
(2, 3, 4, 6)
enter 3 elements234
('2', '3', '4')
Q6. fruits = t=('There',['are','a','few','words'],'that','we','will','use')
("apple", "banana", "cherry") print(t[1][0::2])
print('a' in t[1][0])
(green, yellow, red) = fruits t[1][2]='some'
print(t[1])
print(green) print(t[2::2])
print(yellow) print(t[2][2] in t[1])
print(red) which statement cause an error
OUTPUT t=(1,3,5)
apple print(t+(10,34))#tuple
banana print(t+12) #number
cherry print(t +'abc') #string
print(t+[2,4]) #list
OUTPUT
['are', 'few']
True
['are', 'a', 'some', 'words']
('that', 'will')
True
(1, 3, 5, 10, 34)
error

Q4.WAP to calculate the average of the numbers of the tuple.if t=(23,33,42,55)


Ans:
Q5.WAP to input 4 element tuple and unpack it to four variables .then recreate tuple with swapped as 1st element with 3rd and 2nd
element with 4th element.
Ans:
t=(10,20,30,40)
print("Original tuple is",t)
a,b,c,d=t
t=c, d ,a ,b
print("After swapping" ,t)
OUTPUT
Original tuple is (10, 20, 30, 40)
After swapping (30, 40, 10, 20)
Q6.WAP to add second last element as 41 if t=(12,43,55,76)
t=(12,43,55,76)
l=list(t)
l.insert(3,41)
t=tuple(l)
print(t)
(12, 43, 55, 41, 76)
Q7.WAP to sort first half elements of tuple in ascending order
T=(78,23,45,12,88,45,22,10,11,44) Output:(12,23,45,78,88,45,22,10,11,44)
Ans:
T=(78,23,45,12,88,45,22,10,11,44)
l=list(T)
mid=len(l)//2
l2=l[:mid]
l1=sorted(l2)+l[mid:]
T=tuple(l1)
print(T)
Q8.WAP to input names of a students and store them in a tuple. Also input name from the user and finds if this student is present
in list or not.
Ans:
l=[]
c=0
for i in range(4):
n=input("enter a name")
l.append(n)
t=tuple(l)
print(t)
s=input("enter a name for searching")
for i in t:
if i==s:
print("Student name is",i)
c=1
if c!=1:
print("Student name is not available")
OUTPUT
enter a name sia
enter a name ria
enter a name tia
enter a name zia
('sia', 'ria', 'tia', 'zia')
enter a name for searching tia
Student name is tia

You might also like