0% found this document useful (0 votes)
5 views

LIST MANIPULATION

The document provides an extensive overview of list manipulation in Python, detailing their mutable nature, creation methods, and operations such as accessing, modifying, and deleting elements. It contrasts lists with their immutable counterparts, tuples, and explains various list methods like append, extend, pop, and remove. Additionally, it includes practical examples, solved problems, and programming assignments related to list operations.

Uploaded by

salirnaqvi2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

LIST MANIPULATION

The document provides an extensive overview of list manipulation in Python, detailing their mutable nature, creation methods, and operations such as accessing, modifying, and deleting elements. It contrasts lists with their immutable counterparts, tuples, and explains various list methods like append, extend, pop, and remove. Additionally, it includes practical examples, solved problems, and programming assignments related to list operations.

Uploaded by

salirnaqvi2006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

LIST MANIPULATION

CHECK POINT
1 Why are lists called mutable types?
Lists are mutable ie, their value can be changed by adding or
changing an element in it.For example
L=[1,2,3]
L[1]=4 # changed the element at index 1
L.append(5) # element 5 is added to the list
Hence they are called mutable types in python.
2 What are immutable counterparts of lists?
Immutable counterpart of lists are tuples because their values can’t
be changed.For example
T=(1,2,3)
T[1] =4 #this will raise error
3 What are the different ways of creating lists?
*)L=list( <sequence>)
*)We can initialize the list with values like
L=[ ]
L=[1,2,3]
*) L=eval(input("Enter list elements"))

4 What values can we have in a list? Do they all have to be the same
type?
In lists we can store values of any data type.
No
5 How are individual elements of lists are accessed and changed?
Individual elements of lists are accessed and changed as
L[index]= new value
Eg:
L=[1,2,3]
L[2]=5
print(L)
[1,2,5]
6 How do you create the following lists?
a)[4,5,6]
L=[4,5,6] or L=list([4,5,6])
b)[-2,1,3]
L=[-2,1,3] or L= list([-2,1,3])

c)[-9,-8,-7,-6,-5]
L=[-9,-8,-7,-6,-5] or L =list([-9,-8,-7,-6,-5]) or L=list(range(-9,-4))

d)[-9,-10,-11,-12]
L=[-9,-10,-11,-12] or L =list([-9,-10,-11,-12]) or
L=list(range(-9,-,-1))

e)[0,1,2]
L=[0,1,2] or L =list([0,1,2]) or L=list(range(3))
7 If a =[5,4,3,2,1,0] evaluate the following expressions:
a)a[0]
b)a[-1]
c)a[a[0]]
d)a[a[-1]]
e)a[a[a[a[2] +1]]]
8 Can you change an element of a sequence? What if the sequence is a
string? What if the sequence is a list?
If the sequence type is mutable , then the element can be changed
otherwise not possible
If the sequence is a string , the element can’t be changed.
If the sequence is a list , the elements can be changed.
9 What does a+b amounts to if a and b are lists?
A new list with all the elements of ‘a’ and ‘b’ combined.
10 What does a*b amounts to if a and b are lists?
11 What does a+b amounts to if a is a list and b=5?
a+b will raise Type error
12 Is a string the same as a list of characters?
13 Which functions can you use to add elements to a list?
append( ) , extend( ) , insert( )
14 What is the difference between append() and insert() methods of list?
append( ) method inserts an element to the last of the list .
insert( ) method can insert an element at any position.
15 What is the difference between pop() and remove() methods of list?
pop( ) function delete and return the element of passed index. Index
passing is optional , if not passed , element from last will be deleted.
List.pop(<index>)
remove( ) function removes the first occurence of given item from
the list.
List.remove(<value>)
16 What is the difference between append() and extend() methods of
list?
append( ) function adds a single item to the end of the list.
List.append(<item>)
extend( ) function add multiple elements from a list supplied to it as
argument.
List.extend(<list>)

17 How does the sort() work? Give example.


sort( ) function sorts the items of the list by default in ascending
order. It does not create a new list.
List.sort ( )
To sort in descending order
List.sort(reverse =True)
18 What does list.clear() function do?
The clear( ) function removes all elements from the list.
L=[1,2,3]
L.clear( )
print(L)
o/p
[]

SOLVED PROBLEMS
1 How are lists different from strings when both are sequences?
2 What are nested lists?
3 What does each of the following expression evaluate to?
L = [“These”,”are”, “a” , [“few”,”words”],”that”,”we”,”will”,”use”]

a)L[3:4]
L[3:4][0]
L[3:4][0][1]
L[3:4][0][1][2]
b)”few” in L
c)”few” in L[3]
d)[L[1]] + L[3]
e)L[4:]
f)L[0: :2]
4 What does each of the following expression evaluate to?
L = [“These”,[”are”, “a” ], [“few”,”words”],”that”,”we”,”will”,”use”]
a)len(L)
b)L[3:4] +L[1:2]
c)”few” in L[2:3]
d)”few” in L[2:3][0]
e)”few” in L[2]
f)L[2][1:]
g)L[1] +L[2]
6 Write the most appropriate list method to perform the following

tasks.
a)Delete a given element from the list. Ans)remove( )
b)Delete 3rd element from the list. Ans)pop(2)
c)Add an element in the end of the list. Ans)append( )
d)Add an element in the beginning of the list.
Ans) insert(0,element)
e)Add elements of a list in the end of a list. Ans) extend( )
Assignments
Type A : Short Answer Questions / Conceptual Questions
1 Discuss the utility and significance of Lists, briefly.
Lists in python are used to store elements which cannot be stored
in a single variable. They are similar to arrays from other
programming languages. They are mutable and hence their
elements can be changed. Also they can store elements of different
data types
2 What do you understand by mutability? What does “in place”
memory updation mean?
Mutability means that the elements of the object can be changed in
place. “In place” means that the object dosen’t need to change
memory location to store the new changes.Eg
L=[1,2,3,4]
A=id(L)
L[0] = 5
B=id(L)

3 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
4 If a is [1,2,3]
a)What is the difference (if any) between a*3 and [a,a,a]?
b)Is a*3 equivalent to a+a+a?
c)What is the meaning of a[1:1] =9?
d)What’s the difference between a[1:2] = 4 and a[1:1]=4?
5 What’s a[1:1] if a is a string of at least two characters? And what
if string is shorter?
6 What’s the purpose of the del operator and pop method?
7 What does each of the following expression evaluate to?
L = [“These”,[”are”, “a” , “few”,”words”],”that”,”we”,”will”,”use”]
a)L[1][0::2]
b)”a” in L[1][0]
c)L[:1] + L[1]
d)L[2][2] in L[1]

8 What are list slices? What for can you use them?
List slices are parts of the list.They can be used to get only the
required elements from the list rather than the whole list.
9 Does the slice operator always produce a new list?
The slice operator always produces a copy of the part of the list
that is being slice.
10 Compare list and strings. How are they similar and how are they
different?
11 What do you understand by true copy of a list?
The changes made in one list do not reflect in the other one.
Eg:
A=[1,2,3,4]
B=list(A)
A[0]=5
print(B) #B is still [1,2,3,4] even though A has become [5,2,3,4]
12 An index out of bounds given with a list name causes error, but
not with list slices. Why?
Slicing returns a list , if the indices don’t fall within the range of
the number of elements in the list ,It returns an empty list.
While accessing an element using an index , if the index is out of
range , it cannot return a default value None.

Type B: Application Based Questions


1 What is the difference between following two expressions, if lst
is given as [1,3,5]
i)lst *3
ii)lst *= 3
2 Given two lists
L1=[‘this’,’is’,’a’,’List’] , L2 =[‘this’ , [‘is’,’another’],’List’]
Which of the following expressions will cause an error and why?
a) L1 == L2 b)L1.upper( ) c)L1[3].upper( )
d)L2.upper( ) e)L2[1].upper( ) f)L2[1][1].upper( )
3 From the previous question , give output of expressions that do
not result in error.
4 Given a list L1=[3, 4.5, 12, 25.7, [2, 1, 0, 5], 88]
a)Which list slice will return [12,25.7,[2,1,0,5] ]
b)Which expression will return [2,1,0,5]
c)Which list slice will return[2,1,0,5]
d)Which list slice will return [4.5,25.7,88]
Answer : a)L1[2:5] b)L1[4] c)L1[4:5] d)L1[1: :2]
5 Given a list L1 =[3, 4.5, 12, 25.7, [2,1,0,5], 88] , which function
can change the list to :
a)[3, 4.5, 12, 25.7, 88]
b)[3,4.5,12,25.7]
c)[[2,1,0,5],88]
6 What will the following code result in?
L1=[1,3,5,7,9]
print(L1 == L1.reverse( ) )
print(L1)

7 Predict the output


my_list = [‘p’,’r,’o’,’b’,’l’,’e’,’m’]
my_list[2:3] = [ ]
print(my_list)
my_list[2:5]=[ ]
print(my_list)

8 Predict the output


List1=[13,18,11,16,13,18,13]
print(List1.index(18))
print(List1.count(18))
List1.append(List1.count(13))
print(List1)

Answer: 1
2
[13, 18, 11, 16, 13, 18, 13, 3]
10 Predict the output
a,b,c =[1,2],[1,2],[1,2]
print(a == b)

Answer : True

11 Predict the output of following two parts. Are the outputs same?
Are the outputs different? Why?
a)L1, L2 =[2,4],[2,4]
L3 = L2
L2[1] = 5
print(L3)

Answer: [2,5]
(Reason is L2 and L3 represents the same memory location)
b)L1,L2 = [2,4] ,[2,4]
L3 = list(L2)
L2[1] = 5
print(L3)

Answer : [2,4]
(Reason is L2 and L3 represents the different memory location)

12 Find the errors


L1 =[1,11,21,31]
L2 = L1+ 2
L3 = L1 * 2
Idx =L1.index(45)

13 Find the errors


a) L1=[1,11,21,31]
An=L1.remove(41)

a) L1=[1,11,21,31]
An=L1.remove(31)
print(An + 2)
14 Find the errors
a)L1=[3,4,5]
L2=L1*3
print(L1* 3.0)
print(L2)

b)L1=[3, 3, 8 , 1, 3, 0, ’1’, ’0’, ’2’, ’e’, ’w’, ’e’, ’r’]


print(L1[: : -1])
print(L1[-1:-2:-3])
print(L1[-1:-2:-3:-4])
15 What will be the output of following code?
x=[‘3’,’2’,’5’]
y =’ ‘
while x:
y = y + x[-1]
x = x[: len(x) -1]
print(y)
print(x)
print(type(x) , type(y))

output
523
[]
<class 'list'> <class 'str'>

PROGRAMS
1 Program to find minimum / smallest element from a list of
element along with its index in the list
L=eval(input(“Enter list : ”))
length = len(L)
minele =L[0]
minindx =0
for i in range (1, length):
if L[i] < minele :
minele = L[i]
minindx = i
print(“Given list is :” , L)
print(“The minimum element of the given list is :”)
print(minele,”at index” , minindx)

2 Program to find largest element from a list of element along


with its index in the list (Home Work)
L=eval(input(“Enter list : ”))
length = len(L)
maxele =L[0]
maxindx =0
for i in range (1, length):
if L[i] > maxele :
maxele = L[i]
maxindx = i
print(“Given list is :” , L)
print(“The largest element of the given list is :”)
print(maxele,”at index” , maxindx)

3 Program to print the smallest and largest integer in a list.


Write code without using a loop.
L=eval(input("Enter list : "))
minele=min(L)
maxele=max(L)
print("Largest element =", maxele)
print("Smallest element =", minele)
or
L=eval(input("Enter list : "))
L.sort()
print("Largest element =", L[-1])
print("Smallest element =", L[0])

4 Program to calculate mean of a given list of numbers.


L=eval(input(“Enter list : ”))
length = len(L)
mean = sum = 0
for i in range (0, length):
sum += L[i]
mean = sum/length
print(“Given list is :” , L)
print(“The mean of the given list is :”, mean)
or
L=eval(input("Enter list : "))
length = len(L)
SUM = sum(L)
mean = SUM/length
print("Given list is :" , L)
print("The mean of the given list is :", mean)
5 Program to search for an element in a given list of
numbers.(Linear Search)
L=eval(input(“Enter list : ”))
length = len(L)
element =int(input(“Enter the element to be searched :”))
for i in range (0, length):
if element == L[i] :
print(element ,”found at index”, i)
break
else:
print(element , “Not found in given list “)

6 Program to count frequency of a given element in a list of


numbers.
L=eval(input(“Enter list : ”))
length = len(L)
element =int(input(“Enter element :”))
count = 0
for i in range (0, length):
if element == L[i] :
count +=1
if count == 0:
print(element , “Not found in given list “)
else :
print(element,“has frequency as”, count, ”in the given
list”)
or
L=eval(input(“Enter list : ”))
element =int(input(“Enter element :”))
Count=L.count(element)
print(element,“has frequency as”, Count, ”in the given list”)
7 Program to add the numbers in a list and display the sum
L=eval(input(“Enter list : ”))
length = len(L)
sum = 0
for i in range (0, length): [0,1,2,3,4]
sum += L[i]
print(“Given list is :” , L)
print(“The sum of the given list is :”, sum)
or

L=eval(input(“Enter list : ”))


print(“sum of elements in the list”,sum(L))

8 Program to calculate and display the sum of all the odd


numbers in the list
L=eval(input("Enter list : "))
length = len(L)
sum = 0
for i in range (0, length):
if L[i] % 2 == 1:
sum += L[i]
print("Given list is :" , L)
print("The sum of odd numbers in the given list is :", sum)

9 Given two lists, write a program that prints “Overlapped” if


they have at least one member in common, otherwise prints
“Separated”.
L1=eval(input(“Enter list1 :”))
L2=eval(input(“Enter list2 :”))
len1=len(L1)
len2=len(L2)
for i in range(len1):
ele =L1[i]
if ele in L2:
print(“Overlapped”)
break
else:
print(“Separated”)

10 Write a program to find the second largest number of a list


of numbers.
L=eval(input(“Enter list :”))
length=len(L)
big = secbig = L[0]
for i in range(1, length):
if L[i] > big:
secbig = big
big = L[i]
elif L[i] > secbig:
secbig = L[i]

print(“Largest number of the list : ”, big)


print(“Second Largest number of the list :”,secbig)

11 Write a program that reverses an array of integers ( in


place)
L=eval(input(“Enter list :”))
L.reverse( )
print(L)
or
L=eval(input("Enter list :"))
L=L[: : -1]
print(L)

12 Write a program that inputs two lists and creates a third,


that contains all elements of the first followed by all
elements of the second.
L1=eval(input("Enter list1 elements :"))
L2=eval(input("Enter list2 elements :"))
L3 = L1+ L2
print(L3)

13 Ask the user to enter a list containing numbers between 1


and 12 .Then replace all the entries in the list that are
greater than 10 with 10.
L=eval(input(“Enter list :”))
length=len(L)
for i in range (0,length):
if L[i] > 10 :
L[i] = 10
print(L)
14 Write a program that takes any two lists L and M of the
same size and adds their elements together to form a new list
N whose elements are sums of the corresponding elements in
L and M . For instance, if L=[3,1,4] and M=[1,5,9] then N
should equal [4,6,13].
L=eval(input(“Enter list1 :”))
M=eval(input(“Enter list2 :”))
length = len(L)
N =[ ]
for i in range (0 , length): [0,1,2]
N .append(L[i] + M[i])
print(N)

You might also like