List Example Codes
Creating and Accessing Lists
Ques : Program to print elements of a list ['q','w','e','r','t','y'] in separate lines along with element's both indexes (positive and negative) ?
L = ['q','w','e','r','t','y']
length = len(L)
for a in range (length):
print("At indexes",a,"and",(a-length),"element :",L[a])
List Operators
Ques : Extract two list-slices out of a given list of nummbers, display and print the sum of elements of the first list slice which contains every other element of the list b/w indexes 5 to 15 ?
lst=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
slc1=lst[5:15:2]
slc2=lst[::4]
sum=avg=0
print("Slice 1")
for a in slc1:
sum+=a
print(a,end='')
print()
print("Sum of elements of slice 1:",sum)
sum=0
for a in slc2:
sum+=a
print(a,end='')
print()
avg=sum/len(slc2)
print("Average of elements of slice 2:",avg)
Making a True Copy of Lists
Ques : Write a program to create a copy of a list.In the list's copy, add 10 to its first and last elements. Then display the lists ?
L1 = [17,24,15,30,34,27]
L2 = L1.copy()
print("Original List :",L1)
print("Created copy of the list :",L2)
L2[0] += 10
L2[-1] += 10
print("Copy of the list after changes :",L2)
print("Original List :",L1)
Nested Lists
Ques : Program to create a 2D list ?
Lst = []
r = int(input("How many rows ?"))
c = int(input("How many columns ?"))
for i in range(r):
row = []
for j in range (c):
elem = int(input("Element"+str(i)+","+str(j)+":"))
row.append(elem)
Lst.append(row)
print("List created is: ",Lst)
Ques : Program to traverse a 2D list ?
Lst = []
r = int(input("How many rows ?"))
c = int(input("How many columns ?"))
for i in range(r):
row = []
for j in range (c):
elem = int(input("Element"+str(i)+","+str(j)+":"))
row.append(elem)
Lst.append(row)
print("List created is: ")
print("Lst = [ ")
for a in range(r):
print("\t[",end ="")
for b in range(c):
print(Lst[a][b],end=" ")
print("]")
print("\t]")
Working With Lists
Ques : Write a program that displays options for inserting or deleting elements in a list. If the user chooses a deletion option, display a submenu and ask if the element is to be deleted with value or by using its position or a list slice is to be deleted ?
val=[17,23,18,19]
print('The list is:',val)
while True:
print("Main Menu")
print("1.Insert")
print("2.delete")
print("3.Exit")
ch=int(input("Enter your choice 1/2/3:"))
if ch==1:
item=int(input("Enter item:"))
pos=int(input("Insert at which position:"))
index=pos-1
val.insert(index,item)
print("Success! List now is:",val)
elif ch==2:
print(" Deletion Menu")
print("1.Delete using value")
print("2.Delete using index")
print("3.Delete a sublist")
dch=int(input("Enter choice(1 or 2 or 3):"))
if dch==1:
item=int(input("Enter item to be deleted:"))
val.remove(item)
print("listnow is:",val)
elif dch==2:
index=int(input("Enter index of item to be deleted:"))
val.pop(index)
print("List now is:",val)
elif dch==3:
l=int(input("Enter lower limit of list slice to be deleted:"))
h=int(input("Enter upper limit of list slice to be deleted:"))
del val[l:h]
print("List now is:",val)
else:
print("valid choices are 1/2/3 only.")
elif ch==3:
break
else:
print("valid choice are 1/2/3 only")
Ques : Write a program that inputs a list ,replicates it twice and then prints the sorted list in ascending and descending order ?
val=eval(input("Enter a list:"))
print("Original list:",val)
val=val*2
print("Replication list:",val)
val.sort()
print("Sorted in ascending order :",val)
val.sort(reverse= True)
print("Sorted in descending order :",val)
Ques : Program to find the minimum elements from a list of elements along with its index in the list ?
lst=eval(input("Enter list:"))
length=len(lst)
min_ele=lst[0]
min_index=0
for i in range (1,length):
if lst[i]< min_ele:
min_ele=lst[i]
min_index=i
print("Given list is:",lst)
print("The minimum element of the given list is:")
print(min_ele,"at index",min_index)
Ques : Program to calculate the mean of a given list of numbers ?
lst=eval(input("Enter list:"))
length=len(lst)
mean=sum=0
for i in range (0,length):
sum+=lst[i]
mean= sum/length
print("Given list is:",lst)
print("The mean of the given list is:",mean)
Ques : Program to search for an element in a given list of numbers ?
lst=eval(input("Enter a list:"))
length=len(lst)
element=int(input("Enter element to be searched for:"))
for i in range(0,length):
if element==lst[i]:
print(element,"found at index",i)
break
else:
print(element,"not found in the given list")
Ques : Program to count the frequency of a given element in a list of numbers ?
lst=eval(input("Enter list:"))
length= len(lst)
element=int(input("Enter element:"))
count=0
for i in range(0,length):
if element ==lst[i]:
count+=1
if count==0:
print(element,"not found in the given list")
else:
print(element,"has frequency as",count,"in the given list")
Ques : Program to find frequencies of all elements of a list. Also, print the list odd unique elements in the list and duplicate elements in the given list ?
lst=eval(input("Enter a list:"))
length=len(lst)
uniq=[]
dupl=[]
count=i=0
while i<length:
element= lst[i]
count=1
if element not in uniq and element not in dupl:
i+1
for j in range(i,length):
if element==lst[j]:
count+=1
else:
print("Element",element,"frequency:",count)
if count==1:
uniq.append(element)
else:
dupl.append(element)
else:
i+=1
print("Original list",lst)
print("Unique elements list", uniq)
print("Duplicates elements list",dupl)
Ques : Write a program to check if the maximum element of the lsit lies in the first half of the list or in the second half ?
lst=(eval(input("Enter a list:")))
ln=len(lst)
mx=max(lst)
ind=lst.index(mx)
if ind<=(ln/2):
print("The maximum element",mx,"lies in the 1st half")
else:
print("The maximum element",mx,"lies in the 2nd half")
Ques : Write a program to input two lists and display the maximum element from the elements of both the list combined, along with its index in its list ?
lst1=eval(input("Enter list 1:"))
lst2=eval(input("Enter list 2:"))
mx1=max(lst1)
mx2=max(lst2)
if mx1>=mx2:
print(mx1,"the maximum value is in list 1 at index",lst1.index(mx1))
else:
print(mx2,"the maximum value is in list 2 at index",lst2.index(mx2))
Ques : Write a program that asks the user to input a number of lists to be applied to an existing list. whether the user enters a single number or a list of numbers,the program should append the list accordingly ?
myl = [2,4,6]
print("Existing list is :",myl)
n = eval(input("Enter a number or a list to be appended :"))
if type(n) == type([]) :
myl.extend(n)
elif type(n) == type(1):
myl.append(n)
else:
print("Please enter either an integer or a list.")
print("Appended list is :",myl)
Ncert Solution
Ques : Write a program to find the number of times an element occurs in the list ?
val=eval(input("Enter a list:"))
item=int(input("Enter element:"))
print(item,"occurs in the list",val.count(item),"times.")
Ques : Write a program to read a list of n integers(positive as well as negative).Create two lines, one having all positive numbers and the other having all negative numbers from the given list. Print all three list ?
val=eval(input("Enter a list:"))
plist=[]
nlist=[]
s=len(val)
for i in range (s):
if val[i]<0:
nlist.append(val[i])
elif val[i]>0:
plist.append(val[i])
print("Main list:",val)
print("Positive numbers list:",plist)
print("Negative numbers list:",nlist)
Ques : Write a program to read a list of n integers and find their median ?
val=eval(input("Enter a list:"))
val.sort()
s=len(val)
mid=s//2
if s%2==0:
m1,m2=mid-1,mid
med=(val[m1]+val[m2])/2
else:
med=val[mid]
print("Median of the given list is:",med)
Ques : Write a program to read a list of elements.Modify this list so that it does not contain duplicate elements, i.e. all elements occurring multiple times in the list should appear only once ?
val=eval(input("Enter a list:"))
tmp=[]
print("Original list is:", val)
for a in tmp:
if a not in tmp:
tmp.append(a)
val=list(tmp)
print("List after removing duplicates:",val)
Ques : Read a list of n elements. Pass this list to a function which reverses this list in-place without creating a new list ?
val = eval(input("Entera list :"))
print("Original list :", val)
s = len(val)
mid = s//2
neg = -1
for i in range(mid):
val[i],val[neg] = val[neg],val[i]
neg -=1
print("Reversed list :",val)
Practice Problems
Ques : L is a non-empty list of ints.Print the smallest and the largest integer in L.Write the code without using a loop ?
L=[11,14,265,54,220]
length=len(L)
L.sort()
print("Smallest :",L[0])
print("largest",L[length-1])
Ques : Write a program to find the largest/smallest number in a list / tuple ?
val=eval(input("Enter a list:"))
print("The list is:",val)
mx=max(val)
mn=min(val)
print("Largest number in the list:",mx)
print("Smallest number in the list:",mn)
Ques : Write a program to input a list of numbers and swap elements at the even location with the elements at the odd location ?
val=eval(input("Enter a list:"))
print("Original lsit is",val)
s=len(val)
if s%2 !=0:
s=s-1
for i in range(0,s,2):
print(i,i+1)
val[i],val[i+1]=val[i+1],val[i]
print("List after swapping:",val)
Ques : Write a program to input a list of number is equal to the sum of the cubes of its digit.Find the smallest and the largest such number from the given list of numbers ?
val=eval(input("Enter a list :"))
alist=[]
s=len(val)
for i in range (s):
num=val[i]
csum=0
while num:
dig=num%10
csum+=(dig*dig*dig)
num=num//10
if csum==val[i]:
alist.append(val[i])
print("Largest number(=sum of its digits' cubes):",max(alist))
print("Smallest number(=sum of its digits' cubes):",min(alist))
Ques : Given a list of integers,L,write a program to add the integers and display the sum ?
L=[123,14,22,35,54]
pos=0
sum=0
while pos<len(L):
sum=sum+L[pos]
pos=pos+1
print(sum)
Ques : Given a list of integers,write a program to calculate and display the sum of all the odd numbers in the list ?
L=[43,20,41,55,79]
pos=0
sum=0
while pos< len(L):
if L[pos]%2==1:
sum=sum+L[pos]
pos =pos+1
print(sum)
Ques : Given two lists,write a program that prints "Overlapped" if they have at least one member in common, otherwise print "Separated". You may use the in operator, but for the sake of the exercise, write it using loops ?
listA=eval(input("Enter a list:"))
listB=eval(input("Entera a list:"))
len1= len(listA)
len2= len(listB)
for a in range (len1):
ele=listA[a]
if ele in listB:
print("Overlapped")
break
else:
print("Separated")
Ques : Write a program to find the second largest number of a list of numbers ?
lst = eval(input("Enter list :"))
length = len(lst)
biggest = secondbiggest = lst[0]
for i in range (1, length):
if lst[i] > biggest:
secondbiggest = biggest
biggest = lst[i]
elif lst[i] > secondbiggest:
secondbiggest = lst[i]
print("Largest number of the list :",biggest)
print("Second largest number of the list :",secondbiggest)
Ques : Write a program that inputs a list of numbers and shifts all the zeros to right and all non-zero numbers to left of the list ?
lst =eval(input("Enter list:"))
length=len(lst)
end=length-1
print("Original list:",lst)
i=0
while (i<= end):
ele=lst[i]
if ele==0:
for j in range(i,end):
lst[j]=lst[j+1]
else:
lst[end]=0
end-=1
if lst[i]!=0:
i+=1
print("Zero shifted:",lst)
Ques : Write a program to input a list and an element, and remove all occurances of the given element from the list ?
lst=eval(input("Enter a list:"))
item=int(input("Enter the element to be removed:"))
c=lst.count(item)
if c==0:
print(item,"not in the list")
else:
while c>0:
i=lst.index(item)
lst.pop(i)
c=c-1
print("List after removing ",item,":",lst)
Ques : Write a program to input a list lst and two numbers M and N.Then create a list from those lst elements which are divisible byt both M and N ?
lst= eval(input("Enter a list:"))
lst2=[]
M,N=eval(input("Enter two numbers as M and N:"))
for num in lst:
if (num%M==0 and num%N==0):
lst2.append(num)
print("New created list is:",lst2)