34.Example programs using Lists

Program to read list of names and sort the list in alphabetical order.( university question)
n=int(input("Enter the number of names...."))
names=[]
print("Enter {} names".format(n))
for i in range(n):
    nam=input()
    names.append(nam)
names.sort()
print("names in alphabetical order")
for nam in names:
    print(nam)

Program to find the sum of all even numbers in a group of n numbers entered by the user. (university question)
n=int(input("Enter the number of elements..."))
print("Enter the {} elements".format(n))
l=[] # creating an empty list
for i in range(n):
    x=int(input())
    l.append(x)
sum=0
for i in range(n):
    if l[i]%2==0:
        sum=sum+l[i]
print("Sum of all even numbers",sum)

Program to read a string and remove the given words from the string.
s=input("Enter the string....")
wr=input("Enter the word to remove....")
wrds=s.split(" ")
ns=""
for w in wrds:
    if w!=wr:
        ns=ns+" "+w
print("new string...",ns)
 
Find the average word length of a sentence ( university question)
sentence=input("Enter a sentence: ")
listOfWords=sentence.split()
print("There are", len(listOfWords), "words.")
sum=0
for word in listOfWords:
    sum += len(word)
print("The average word length is",sum/len(listOfWords))
 

Program to read list of numbers and find the median
#We can find median by sorting the list and then take the middle element. If the list contains even number of elements take the average of the two middle elements.
n=int(input("Enter how many numbers...."))
print("Enter {} numbers....".format(n))
lst=[]
for i in range(n):
   x=int(input())
   lst.append(x)
lst.sort()
print(lst)
mid=n//2
if n%2==1:
   print("Median",lst[mid])
else:
   print("Median",(lst[mid]+lst[mid-1])/2)

Finding the mode of list of numbers(A number that appears most often is the mode.)
l=[]
n=int(input("Enter n.."))
print("Enter the numbers..")
for i in range(n):
    x=int(input())
    l.append(x)
c=[]
e=[]
for x in l:
    if x not in e:
        c.append(l.count(x))
        e.append(x)
mc=max(c)
ne=len(c)
i=0
print("mode..")
while i<ne:
    if c[i]==mc:
        print(e[i])
    i+=1

Program to remove all duplicate elements from a list
lst=[]
n=int(input("enter how many numbers.."))
print("Enter elements...")
for i in range(n):
    x=int(input())
    lst.append(x)

nlst=[]
for x in lst:
    if x not in nlst:
        nlst.append(x)
print("new list after removing duplicates")
print(nlst)

Consider a list consisting of integers, floating point numbers and strings. Separate them into different lists depending on the data(university question)
il=[]
fl=[]
sl=[]
l=[12,23.5,'klf',34,4343,34.566,3+3j,'ddldl',35]
for i in l:
  if type(i)==int:
    il.append(i)
  if type(i)==str:
    sl.append(i)
  if type(i)==float:
    fl.append(i)
print("Integer list")
print(il)
print("Float list")
print(fl)
print("String List")
print(sl)

Write a Python program to read list of positive integers and separate the prime and composite numbers (university question)
def prime(n):
        flag=1
        for i in range(2,n//2+1):
                if n%i==0:
                        flag=0
                        break
        return flag    
pl=[]
cl=[]
l=[]
n=int(input("Enter n.."))
print("Enter the numbers..")
for i in range(n):
    x=int(input())
    l.append(x)
for i in l:
  if prime(i):
          pl.append(i)
  else:
          cl.append(i)
print("prime list")
print(pl)
print("composite list")
print(cl)  
Write a Python program to read a list of numbers and sort the list in a nondecreasing order without using any built in functions. Separate function should be written to sort the list wherein the name of the list is passed as the parameter
def sortlist(lst,n):
    for i in range(n-1):
        for j in range(i+1,n):
            if lst[i]>lst[j]:
                lst[i],lst[j]=lst[j],lst[i]
n=int(input("Enter how many numbers...."))
print("Enter {} numbers....".format(n))
lst=[]
for i in range(n):
    x=int(input())
    lst.append(x)
sortlist(lst,n)
print("sorted List is")
print(lst)

Check if the items in the list are sorted in ascending or descending order and print suitable messages accordingly. Otherwise, print “Items in list are not sorted” ( university question)

# initializing list
list = [ 5, 14, 11, 10]

# printing original list
print ("Original list : " + str(list))

# using sort() to
# check sorted list
flag1 = 0
flag2 = 0
list1 = list[:]
list2=list[:]
list1.sort()
list2.sort(reverse=True)
print(list1)
print(list2)
if (list1 == list):
flag1 = 1
if(list2 == list):
   flag2=1 
# printing result
if (flag1) :
print ("Yes, List is sorted in Asceding order.")
elif(flag2) :
    print ("Yes, List is sorted in Desceding order.")
else:
print ("No, List is not sorted.")
 
Write a python code to input n numbers and calculate sum of cubes of each number and store it in a list.( university question)

n=int(input("Enter the number of elements..."))
print("Enter the {} elements".format(n))
l=[] # creating an empty list
for i in range(n):
    x=int(input())
    l.append(x)
sum=0
for i in range(n):
    sum=sum+l[i]**3
print("Sum of cubes of  numbers",sum)

Write a Python program to check whether a list contains a sublist.(University Question)
Eg. Input 1: my_list = [3,4,5,2,7,8] , sub_list = [2,7]
output 1: True
input 2: my_list = [3,4,5,2,7,8] , sub_list = [5,7]
output 2: False

print('enter size of my_list')
n1=int(input())
print('Enter my_list')
my_list=[int(input()) for i in range(n1) ]

print('enter size of sub_list')
n2=int(input())
print('Enter sublist_list')
sub_list=[int(input()) for i in range(n2) ]

flag=0
for i in range(n1+1):
    if my_list[i:i+n2]==sub_list:
        flag=1
        break
if flag:
    print("Sublist TRUE")
else:
    print("Sublist FALSE")

A mobile app records daily temperatures (as float values) entered by a user. Write a code snippet that stores these in a list, converts each to an integer for quick preview, and prints them in a tabular format with proper alignment.(university question)

# Sample list of daily temperatures as float values
daily_temperatures = [30.5, 28.9, 31.2, 29.6, 27.3, 32.8, 30.1]

# Print the header
print(f"{'Day':<5} {'Temperature (°C)':<20} {'Quick Preview (°C)':<20}")
print("-" * 50)

# Print each day's temperature with integer conversion
for i, temp in enumerate(daily_temperatures, start=1):
    print(f"{i:<5} {temp:<20.1f} {int(temp):<20}")

Describe how Python supports arithmetic and comparison operations.Your team is developing a console-based student mark analyzer. The input is taken as a string of comma-separated marks. Demonstrate how to:

1. Parse and convert the input into numeric form.
2. Classify each mark as "Fail", "Pass", or "Distinction" based on thresholds using appropriate control structures.
3. Format and print the output with aligned columns. ( University question)

🔹 Console-Based Student Mark Analyzer

Below is a simple Python program that:

  1. Takes a comma-separated string of marks.

  2. Converts the input into numeric form.

  3. Classifies each mark as "Fail" (below 40), "Pass" (40–74), or "Distinction" (75+).

  4. Prints the results in aligned columns.

# Step 1: Take input
input_str = input("Enter comma-separated marks: ")  # e.g., "78, 45, 32, 90, 60"

# Step 2: Parse and convert to numeric form
marks = [int(mark.strip()) for mark in input_str.split(',')]

# Step 3: Classify using control structures
results = []
for mark in marks:
    if mark < 40:
        status = "Fail"
    elif mark < 75:
        status = "Pass"
    else:
        status = "Distinction"
    results.append((mark, status))

# Step 4: Format and print output
print("\n{:<10} {:<15}".format("Mark", "Classification"))
print("-" * 25)
for mark, status in results:
    print("{:<10} {:<15}".format(mark, status))

Output
Enter comma-separated marks: 78, 45, 32, 90, 60

Mark       Classification
-------------------------
78         Distinction    
45         Pass           
32         Fail           
90         Distinction    
60         Pass           

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

1.Python Introduction