Simplifying 300 Python Programs on the list Questions- 1 to 30.

Simplifying 300 Python Programs on the list Questions- 1 to 30.

"Embark on a transformative journey as I dive deep into the realm of Python lists. Over the next 90 days, join me as I unravel the secrets of list man

Table of contents

I am a Python lover and daily I am solving 10 Python programs, I have set the goal to master Python in 90 Days.

I will be sharing those with the available solutions.

Q1- 1. Write a Python program, to sum up all the items in a list.

  • first, we need to take an item from the list one by one and add them.

  • we can take any variable here we have taken- i and, this variable will take items from the list one by one in a for loop.

  • and we will add up this value to another variable of integer type taking here as add.

  • if you want to see how for loop works I have another blog please go below to below blog link.

  • Click here to learn Python for a loop.

ls=[1,2,3,4,5,6,7,8,9,10] 
add=0 
for i in ls:
  add=add+i
print(add)

Q2- Write a Python program to multiply all the items in a list.

STEPS:

  • we will take a variable let's take var=1.

  • we will take values one by one from the list by iterating the loop over the list.

  • we will multiply taken values from for loop to variable var.

Flow Chart:

ls=[1,2,3,4,5,6,7,8]
var=1
for i in ls:
  var=var*i
print(var)

Q3- Write a Python program to get the largest number from a list.

STEPS:

  • so to find the largest number in a list we can use lots,s of methods to do that.

  • First Method: in this method, we will assume that the first number in the list is the largest number and we will compare the first number to all the numbers on the list, if another number will come the largest number we will assign that number as first number through a variable and loop will Conti...

  • Second Method: in the second method we will use the max function directly on the list to identify the maximum number in the list.

First Method:

ls=[1,2,3,4,5,6,7,8]
var=ls[0]
for i in ls:
  if var<i:
       var=i
print(var)

Second Method:

ls=[1,2,3,4,5,6,7,8]
max_number=max(ls)
print(max_number)

Q4- Write a Python program to get the smallest number from a list.

  • You can use the same explanation and same methods as above to check the smallest number as well.

  • we can iterate a loop over the list and assume that the first number is the smallest number if another number is found to be small we assign that number as a first number through a variable.

we can use the second method as well but the function to use that is min.

ls=[1,2,3,4,5,6,7,8]
var=ls[0]
for i in ls:
  if var>i:
      var=i
print(var)
ls=[1,2,3,4,5,6,7,8]
min_number=min(ls)
print(min_number)

Q5- Write a Python program to count the number of strings from a given list of strings.

if The string length is 2 or more and the first and last characters are the same. Sample List : ['abc', 'xyz', 'aba', '1221']

STEPS:

  • so in this program basically one list is given we need to count the number of strings from that list of strings, condition is string length should be equal to 2 or greater than 2 and its last and first characters should be the same.

  • so in this program, we can use for loop to iterate over a list with a variable - var, this var variable will be assigned a string from the list one by one.

  • then we can apply the if, else condition to check the weather length of var>=2, and the first character and last character of var are the same.

ls=['abc','xyz','aba','1221'] 
for var in ls:
   if len(var)>=2 and var[0]==var[-1]:
        print(var)

Q6- Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.

Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

STEPS:

  • so in this program, we have been given a list, where in the list we have multiple non-empty tuples.

  • now we need to sort the list in such a way that the last element of the tuple is sorted in increasing order.

  • First Method:

for solving this we can use the sorted function, which can sort any iterator object, here list is the iterator object.

help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
ls= [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] 
new_ls=sorted(ls,key=lambda x:x[-1])
pring(new_ls)
#Result
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
  • so as you can see above sorted function requires three arguments - sorted(iterable, /, *, key=None, reverse=False)

  • out of which the second and third arguments are optional as * is mentioned before them.

  • you can define any key as a function, we have len, lambda.

  • for example, consider you want to sort the list on the basis of the length of the strings, you can use key=len

ls=["my","name","is","kapil"]
new_ls=sorted(ls,key=len)
print(new_ls)
#Result
['my', 'is', 'name', 'kapil']
#if you want to sort it without any key it will sort it with alphabatical order
ls=["my","name","is","kapil"]
new_ls=sorted(ls)
print(new_ls)

#if you want to sort it in reverse direction use reverse=True.
ls=["my","name","is","kapil"]
new_ls=sorted(ls,reverse=True)
print(new_ls)
  • Second Method:

  • in the list class itself, we have a sort method available you can use that as well.

  • How to check all the available methods in the list class use the dir function.

dir(list)
['__add__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
  • the methods which are starts from (__) and end with (__) are called as magic methods, these methods we can not call are called automatically from the list class of objects for example- __add__

  • other one we can use which does not start and ends with (__).

  • so you can see we have a sort method available in the list class.

  • Now the question is how to use that method for that we have a help function.

help(list.sort)
Help on method_descriptor:

sort(self, /, *, key=None, reverse=False)
    Sort the list in ascending order and return None.

    The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
    order of two equal elements is maintained).

    If a key function is given, apply it once to each list item and sort them,
    ascending or descending, according to their function values.

    The reverse flag can be set to sort in descending order.
  • so it takes three arguments- sort(self, /, *, key=None, reverse=False)

  • forget about yourself right now we will talk about it later that will be available in every method of any class.

  • other two we have key and reverse, there are used in the same way as we can use in the sorted function.

ls= [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] 
ls.sort(key=lambda x:x[-1])
print(ls)
  • Result:
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

Q7- Write a Python program to remove duplicates from a list.

STEPS:

  • ls=[1,2,3,4,9,9,5,5,5,6,7], in the given list we have multiple items available in which lots of items are duplicate items.

  • now we need to remove them.

  • First Method: in this method, we can convert the list into the set.

  • but in the set problem, the set can destroy the order in which the list is.

ls=[1,2,3,4,9,9,5,5,5,6,7]
s=set(ls)
print(s)
  • Result:
{1, 2, 3, 4, 5, 6, 7, 9} 
#you can see the order of the list and the order of the set
#not the same, set basically elements duplicate items.
  • Second Method:

  • in this second method what we can do is, we will iterate a loop over a list with the variable - var, and we will append the item to a list by applying a condition, if the item is already available do not append if not available append it.

  • let's see below:

ls=[1,2,3,4,9,9,5,5,5,6,7]
new_ls=[] #taking empty list, we will append the item in this list.
for var in ls:   #loop
  if var not in new_ls: #condition 
    new_ls.append(var)
print(new_ls)
#condition: if var is not available in new_ls append the var in new_ls
#Result
[1, 2, 3, 4, 9, 5, 6, 7] #here the order is not destroyed.
  • Flow Chart:

  • you can write the same program in another way as well.

ls=[1,2,3,4,9,9,5,5,5,6,7]
new_ls=[]
for var in ls:
  if var in new_ls:
     pass
  else:
    new_ls.append(var)
print(new_ls)
#if any item of ls is available in new_ls do nothing else if item
#is not available of ls appned that item in new_ls
#pass in if condition does nothing whenever we need to write the
#if or else condition without any statement you can put pass there.
  • Third Method:

  • in the third method, we can take an empty dictionary, and then we can append the items to the dictionary.

  • dictionary does not work on the basis of index, it works on the basis of key: value.

  • Let's take a look at a dictionary.

  • d={'id':101, 'name':'kapil', 'city':'Agra'}

  • so the above dictionary contains three items, id name, and city, and their values are defined.

  • so, in the same way, we can create a dictionary and we can the items and that along with item count.

  • Let's see below.

ls=[1,2,3,4,9,9,5,5,5,6,7] #given list of items.
d={} #taking a empty dictionary.
k=d.keys() #defining that k will represent the keys in the dictionary
v=d.values() #defining that values will be represented by v
for var in ls:
  if var in k: #this checks if any key(k) in dictionary (d) is 
    d[var]=d[var]+1 
  else:
    d[var]=1
print(d)
print(k)
#Result
{1: 1, 2: 1, 3: 1, 4: 1, 9: 2, 5: 3, 6: 1, 7: 1}
dict_keys([1, 2, 3, 4, 9, 5, 6, 7])
  • I hope understood the concept if not let me know in the comment section I will explain it.

Q8- Write a Python program to check if a list is empty or not.

STEPS:

  • to check if a list is empty or not you can check by two ways at least.

  • Method 1st: check the length of the list, if the length is zero that means the list is empty, else list is full.

  • Method 2nd: it can be directly checked by if, else condition.

  • Let's see below.

ls=[]
if len(ls)>=0:
  print("list is not empty")
else:
  print("list is empty")
ls=[]
if ls:  #this checkes if list exists with the name ls(full list).
 print("list is not empty")
else:
  print("list is empty")
#you can write the same above code in other way as well.
ls=[]
if not ls: 
  print("list is empty")
else:
  print("list is not empty")
#this is the beauty of python to check these kind of stuff

Q9- Write a Python program to clone or copy a list.

STEPS:

  • 1st Method:

  • we have copy method available in the list, as already explained how to check all the available methods for any class using the dir function.

  • so using copy function we can create a copy of any list.

ls=[1,2,3,4,5,6,7]
new_ls=ls.copy()
print(new_ls)
  • 2nd Method:
ls=[1,2,3,4,5,6,7]
new_ls=ls #single (=) is the assignment operator.
print(new_ls)

Q10- Find the list of words that are longer than n from a given list of words.

  • so we need to make a new list, in that list, all the words will be available which are longer than n (n is any integer value, let's say 3) from a given list.

  • Let's say the list ls=['the', 'quick', 'brown', 'fox']

  • so the solution can be to iterate a loop over it and find the words with a length greater than 3.

ls=['the','quick','brown','fox']
new_ls=[]
for var in ls:
  if len(var)>3:
     new_ls.append(var)
  else:
    pass
print(new_ls)
#Result
['quick', 'brown']

Q11- python program for finding a given number is a prime number?

  • we all know that 1 is neither a prime nor composite number, so if the number is given 1, it will be treated as non-prime and variable is_prime will be set to False.

  • we all know that 2 is a prime number, hence if the number 2 is given by the user we will set the is_prime=True.

  • if any other number is given so as per the definition of prime number: a number which is completely divisible by 1 and itself is called prime.

  • by default all the numbers are divisible by 1 and itself so we will check if that number is divisible by any number in the range between 2 and that number.

  • for example- 6, 6 is divisible by 1 and 6 by default, but we will check if 6 is divisible by any number between 2 to 6, then it becomes non-prime, hence we are setting variable is_prime=False.

  • Now in the last, we are breaking the loop and printing the variable according to the code execution.

n=int(input("please provide a number: "))
is_prime=True
if n==1:
 is_prime=False
elif n==2:
  is_prime=True
else:
  for i in range(2,n):
     if n%i==0:
        is_prime=False
        break
if is_prime==True:
  print("given number is a prime number")
else:
  print("given number is not a prime number")

Q12- Write a Python function that takes two lists and returns True if they have at least one common member.

STEPS:

  • 1st Method:

  • so in this program, we have been given two lists, where we need to check if any of the members of both lists are common.

  • so for that what we can do is, we can iterate a loop over a list and check that any member is available on the second list using the if-else condition.

ls_a=[1,2,3,4,5]
ls_b=[6,7,8,9,10]
for i in ls_a:
  if i in ls_b:
      print("True")
      break
else:
  print("False")
  • 2nd Method:

  • in this method, we can convert the lists into sets and we can find out common members from these two sets.

  • for that let's see if any method is available in the set for finding the common members between sets.

dir(set)
['__and__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__iand__',
 '__init__',
 '__init_subclass__',
 '__ior__',
 '__isub__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__or__',
 '__rand__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__ror__',
 '__rsub__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__xor__',
 'add',
 'clear',
 'copy',
 'difference',
 'difference_update',
 'discard',
 'intersection',
 'intersection_update',
 'isdisjoint',
 'issubset',
 'issuperset',
 'pop',
 'remove',
 'symmetric_difference',
 'symmetric_difference_update',
 'union',
 'update']
  • yes, we have an intersection method available for finding the common members between two sets.

  • How to use that let,s see.

Help on method_descriptor:

intersection(...)
    Return the intersection of two sets as a new set.

    (i.e. all elements that are in both sets.)
ls_a=[1,2,3,4,5,9]
ls_b=[6,7,8,9,10]
s1=set(ls_a)
s2=set(ls_b)
common=s1.intersection(s2)
print(common)
  • 3rd Method:

  • in this method, we can take an element from list-1 and compare it with all the elements of list-2, if both match then both lists have a common member.

  • Let,s try it.

ls_a=[1,2,3,4,5,10]
ls_b=[6,7,8,9,10]
is_common=False
for i in ls_a: 
   for j in ls_b:
       if i==j:
        is_common=True
        break
if is_common==True:
   print("True")
else:
  print("False")
#in the first iteration, i=1 and j=6, i=1,j=7 like this goes for
#all the elements of j.

Q13- Write a Python program to print the numbers of a specified list after removing even numbers from it.

STEPS:

  • we need to remove the even numbers from the list and then print that list with the remaining elements.

Method:

  • we will run a loop over the given list and make a condition that will check if the item is not an even number and then append that item to the empty list, which can serve our purpose.

  • number, which is completely divisible by 2 is an even number.

ls=[1,2,3,4,5,6,7,8,9,10]
new_ls=[] #taking empty list.
for i in ls:  #running a loop over a list, i=1,2,3,4..
   if i%2==0: #checking if item is completely divisible by 2.
       pass #doing nothig if it is a event number
   else:
     new_ls.append(i) #appending the number in the new_ls, if not even number
print(new_ls) #finally priting the generated list.
#result
[1, 3, 5, 7, 9]

Q14- Write a Python program to shuffle and print a specified list.

STEPS:

  • Shuffle, means we need to rotate the items of the list from their position to another position.

1st Method:

  • in this method: what we can do is, take one item from the list and replace it with the second item, but when you will be going to replace the last item with its next item, it will give an index error. so we will apply the loop only n-1th item.

  • but in this, there is a problem, by our above method, the first item is replaced by the second, the second is replaced by the third, and so on, but in the last, we need to replace the last item with the first item.

  • so we need to take the two lists of the same copies and replace the last item.

  • Let's visualize it.

ls=['red','green','orange','blue','white']
for i in range(len(ls)):
  ls[i]==ls[i+1]
#here you will get the error because when it will going to replace 
#last item that is white to whom it will replace we do not have any
#next item, so will restrict our loop to n-1th item.
ls=['red','green','orange','blue','white']
ls_copy=ls.copy()
for i in range(len(ls)-1):
  ls[i]=ls[i+1]
ls[-1]=ls_copy[0]
print(ls)
#Result
['green', 'orange', 'blue', 'white', 'red']

2nd Method:

  • in this method, we can directly take a class shuffle from a random module.

  • right now, just forget about the module, we will understand this later, just consider modules in Python are already written codes that can help you in your code.

  • so we need to import them into our code using import.

from random import shuffle
color= ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
shuffle(color)
print(color)
#Result:
['White', 'Yellow', 'Pink', 'Red', 'Black', 'Green']

Q15-Write a Python program to generate and print a list of the first and last 5 elements where the values are square numbers between 1 and 30 (both included)

STEPS:

  • So here, we have been asked to create a list of square 1 to 30 numbers (including 1 and 30).

  • printing the first 5 and last 5 elements from that list.

  • for 1 to 30 numbers, we can use the range function - range(1,31) - it will include 1 and 30 both.

  • make every numbered square while looping in that list.

  • see below:

new_ls=[]  #creates empty list
for i in range(1,31): #running a loop over numbers 1 to 30.
  new_ls.append(i**2) #squaring each item and appending it in the new_ls list.
print(f"strting 5 elements are: {new_ls[0:6]}")  #printing first 5 elements.
print(f"ending 5 elements are: {new_ls[-1:-6:-1]}") #printing last 5 elements.
#Result
[1, 4, 9, 16, 25, 36]
[900, 841, 784, 729, 676]
  • you can also write the same program as below.
new_ls=[]  #creates empty list
for i in range(1,31): #running a loop over numbers 1 to 30.
     i=i**2 #squaring the item.
     new_ls.append(i) #appending the item in new_ls.
print(f"strting 5 elements are: {new_ls[0:6]}")  #printing first 5 elements.
print(f"ending 5 elements are: {new_ls[-1:-6:-1]}") #printing last 5 elements.

Q16- Write a Python program to check if each number is prime in a given list of numbers. Return True if all numbers are prime otherwise False.

as we have already completed the program for prime numbers, this can be done as below.

iterate a loop over the list, separate the prime and non-prime numbers in the two lists, and check the length of the list of non-prime numbers.

if the list length is zero then all the numbers are prime only.

Q17-Write a Python program to generate all permutations of a list in Python.

  • Permutation: A permutation refers to the arrangement of objects in a specific order. It considers the order or sequence in which objects are selected or arranged. In a permutation, the order of the elements is crucial, and changing the order will result in a different permutation.

  • for finding the permutation we have a permutation class from the itertools module.

from itertools import permutations
ls=[1,2,3,5]
perm=permutations(ls)
print(list(perm))

OR

import itertools
ls=[1,2,3,5]
perm=itertools.permutations(ls)
print(list(perm))

Q18-Write a Python program to calculate the difference between the two lists.

Method:

  • we do not have a direct method to check the difference between the two lists.

  • we need to convert the lists into sets then only we can check the difference between the two lists?

ls1=[1,2,3,4,5,6,7]
ls2=[7,8,9,10,11,6,7,8]
set1=set(ls1)
set2=set(ls2)
print(set2.difference(set1))
print(set1.difference(set2))
#result
{8, 9, 10, 11}
{1, 2, 3, 4, 5}

Q20-Write a Python program to access the index of a list.

STEPS:

  • to check the index of a single item in the list we can use the index method.
dir(list)
['__add__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort'
help(list.index)
Help on method_descriptor:

index(self, value, start=0, stop=9223372036854775807, /)
    Return first index of value.

    Raises ValueError if the value is not present.
  • so, we need to give value, to check the index.
ls=['a','b','c','d','e','d','c','a']
ls.index('a')
0
#but it is only giving the index of first occurances of 'a' only.
#for finding the index of all occurances of a we need to iterate the loop over list as below.
ls=['a','b','c','d','e','d','c','a']
for i in range(len(ls)):
  if ls[i]=='a':
    print("index of a in list is: ",i)
#result
index of a in list is:  0
index of a in list is:  7

so to find the index of each item in the list iterate the loop as below.

ls=['a','b','c','d','e','d','c','a']
for i in ls:
 print(f"index of {i} is {ls.index(i)}
  • In the above problem, the index of the first occurrence of 'a' is shown.

  • for checking the index of first every item in the list, we can use enumerate function.

ls=['a','b','c','d','a','e','f']
new_ls=enumerate(ls)
for index,value in new_ls:
  print("Index:", index,end=" ")
  print("Value:", value)
#Result

#Result
Index: 0 Value: a
Index: 1 Value: b
Index: 2 Value: c
Index: 3 Value: d
Index: 4 Value: a
Index: 5 Value: e
Index: 6 Value: f

Q21-Write a Python program to convert a list of characters into a string.

  • for converting the characters of the list into a string, we can use the join method of the str class.
Help on method_descriptor:

join(self, iterable, /)
    Concatenate any number of strings.

    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.

    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  • so we need an iterable - list, tuple, dictionary, etc...

  • Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

  •   ls=['p','y','t','h','o','n']
      new_ls="".join(ls)
      print(new_ls)
    
#Result
python

Q22-Write a Python program to find the index of an item in a specified list.

We have already covered this in the earlier examples.

ls=['p','y','t','h','o','n','y']
new_ls=[]
for i in range(len(ls)):
  if ls[i]=='y':
    new_ls.append(i)
print(new_ls)

Q23-Write a Python program to flatten a shallow list.

I am finding a good solution for this, I will write the solution to it later.

Q24-Write a Python program to append a list to the second list.

  • for appending the list to another list as we have already seen, we have an appending method to do so.

      ls1=[1,2,3,4,5,6,7,8,9,10]
      ls2=["red","green","black"]
      for i in ls2:
       ls1.append(i)
    
      #Result
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'red', 'green', 'black']
    

    Q25-Write a Python program to select an item randomly from a list.

  • to select an item randomly from a list, we have a random module.

import random
help(random.choice)
Help on method choice in module random:

choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.
import random
color_list = ['Red', 'Blue', 'Green', 'White', 'Black']
print(random.choice(color_list))

Q26-Write a Python program to check whether two lists are circularly identical.

  • for checking, if the given lists are circularly identical.

  • we need to keep the first list stationary and compare its items by rotating the second list.

  • please consider the below two lists for an explanation.

  • circularly rotating means, items of the lists are rotated from the start of the list.

  • Now, first, we need to write the code to rotate a list, which means we need to break a list into two lists, in the first list take the items from the first to the end item and add the first item in the last.

  • in the second rotation, we need to take two lists, wherein the first list of items will be from the second to the last, and the second list will contain the last two items. so for doing that, we can create a for loop as below.

      list1 = [10, 10, 0, 0, 10]
      for i in range(len(list1)):
        new_ls=list1[i:]+list1[:i]
        print(new_ls)
    
      #Result
      [10, 10, 0, 0, 10]
      [10, 0, 0, 10, 10]
      [0, 0, 10, 10, 10]
      [0, 10, 10, 10, 0]
      [10, 10, 10, 0, 0]
    
      #final code as per our question.
      list1 = [10, 10, 0, 0, 10]
      list2 = [10, 10, 10, 0, 0]
      if len(list1)!=len(list2):
       print("both the lists are not circularly identical")
      else:
       for i in range(len(list2)):
         shifted_list=list2[i:]+list2[:i]
         if list1==shifted_list:
           print("True")
    

    Q27-Write a Python program to find the second smallest number in a list.

we have already covered in Q4, that how we can find the first smallest number, please see the code below that we used in Q4.

ls=[1,2,3,4,5,6,7,8]
var=ls[0]
for i in ls:
  if var>i:
      var=i
print(var)
  • to find the second smallest number in the list, we can make the first minimum number =second minimum number once the first minimum number is found. and we will search for the second minimum number as below.

      ls = [5, 2, 9, 1, 7]
      first_minimum=ls[0]
      second_minimum=float('inf') #assining the maximum number.
      for i in ls:
        if first_minimum>i:
          second_minimum=first_minimum
          first_minimum=i
      print(second_minimum)
    
      #Result
      2
    
      #OR
      ls = [5, 2, 9, 1, 7]
      first_minimum = min(ls)
      ls.remove(first_minimum)
      second_minimum = min(ls)
    
      print("The second minimum value is:", second_minimum)
    

    Q28- Write a Python program to find the second largest number in a list.

    it can be done as above we have done.

    Q29-Write a Python program to get unique values from a list.

    as we have already discussed in the earlier example-Q7.

    for finding unique items or getting a new list after removing the duplicates.

    Q30-Write a Python program to get the frequency of elements in a list.

    for getting the frequency of the items in the list, we can create a dictionary of the items with their frequency as below. the explanation is also covered in the Q7- Third method.

      ls=[1,2,3,3,4,4,5,6,7,8,8,9,10,11,1,2,3]
      d={}
      k=d.keys()
      for i in ls:
        if i in k:
          d[i]+=1
        else:
          d[i]=1
      for element,frequency in d.items():
        print("Element:",element,end=" ")
        print("Frequency:",frequency)
    
      #Result
      Element: 1 Frequency: 2
      Element: 2 Frequency: 2
      Element: 3 Frequency: 3
      Element: 4 Frequency: 2
      Element: 5 Frequency: 1
      Element: 6 Frequency: 1
      Element: 7 Frequency: 1
      Element: 8 Frequency: 2
      Element: 9 Frequency: 1
      Element: 10 Frequency: 1
      Element: 11 Frequency: 1