Simplifying 300 Python Programs on the list- Questions 31-40.
"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.
Table of contents
- Q31-Write a Python program to count the number of elements in a list within a specified range.
- Q32-Write a Python program to check whether a list contains a sublist.
- Q33-Write a Python program to generate all sublists of a list.
- Q34-Write a Python program to create a list by concatenating a given list with a range from 1 to n.
- Q35-Write a Python program to find common items in two lists.
- Q36-Write a Python program to change the position of every n-th value to the (n+1)th in a list.
- Q37- Write a Python program to convert a list of multiple integers into a single integer.
- Q38- Write a Python program to split a list based on the first character of a word.
- Q39- Write a Python program to create multiple empty lists.
- Q40- Write a Python program to find missing and additional values in two lists.
Q31-Write a Python program to count the number of elements in a list within a specified range.
STEPS:
First Method: in this method, we can make a dictionary that can store items on the list and their frequency.
from that list, we can store the number of elements from that dictionary in another dictionary or list and print those.
Block Code:
ls=[1,2,3,4,5,6,7,8,9,10,40,40,50,60,60,80,90]
d={}
new_ls=[]
k=d.keys()
for i in ls:
if i in k:
d[i]=d[i]+1
else:
d[i]=1
for key,value in d.items():
if key>=40 and key<70:
new_ls.append(key)
print(new_ls)
#Result
[40, 50, 60]
- so there are three elements greater than 40 and less than 70, which is a specific range here.
Second Method:
- in this method, we can convert the list into set to remove the duplicates and find the elements of a specified range.
ls=[1,2,3,4,5,6,7,8,9,10,40,40,50,60,60,80,90]
s1=set(ls)
new_ls=[]
for i in s1:
if i>=40 and i<70:
new_ls.append(i)
print(new_ls)
#Result will be same as above.
Q32-Write a Python program to check whether a list contains a sublist.
to check if a list contains a sublist, iterate a loop.
ls1=[1,2,3,4,5,6,7]
ls2=[3,4,8]
ls3=[]
for i in ls2:
if i in ls1:
ls3.append(i)
if ls3==ls2:
print("True")
else:
print("False")
if there are multiple lists, you can choose to use the below loop as well.
ls1=[1,2,[3,4],5,6,7]
ls2=[3,4]
if ls2 in ls1:
print("True")
else:
print("False")
Q33-Write a Python program to generate all sublists of a list.
to generate all the sublists of a list.
that means we need to combinations of the multiple items in the list.
so find all the combinations we need to use itertools module, there we can have permutations and combination functions.
import itertools
ls=['x','y','z']
temp=[]
for i in range(1,len(ls)+1):
new_ls=itertools.combinations(ls,i)
temp.append(list(new_ls))
print(temp)
#Result
[['x'], ['y'], ['z'], ['x', 'y'], ['x', 'z'], ['y', 'z'], ['x', 'y', 'z']]
Q34-Write a Python program to create a list by concatenating a given list with a range from 1 to n.
we need to create a list, by a given list, such that generated list should have followed by numbers.
for example: Given list = [p,q], let's say the user gives n=5, so the generated list should be = [p1,q1,p2,q2,p3,q3,p4,q4,p5,q5]
in this case, we can take two loops.
iterate a loop with the range(1,n+1), if n=4 is given, then the range function will provide the values as = 1,2,3,4,5.
range(): range function can generate a range as per the below condition.
start=0(by default) if not given.
last= n-1
step=1(by default) if not given.
Take Some Examples:
range(5): start=0, end=5=5-1=4, and step=1 ==> (0,1,2,3,4)
range(1,5): start=1, end=5-1=4, and step=1 ==> (1,2,3,4)
range(1,5,2): start=1, end=5-1=4, step=2 ==> (1,3)
in the inner loop, we can take values from the given list and add 1,2,3... like this taken from the outer loop.
ls=['p','q']
n=int(input("please provide a number: "))
new_ls=[]
for i in range(1,n+1):
for j in ls:
new_ls.append(j+str(i))
print(new_ls)
#Result:
['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4']
#OR
ls=['p','q']
n=int(input("please provide a number: "))
new_ls=[]
for i in ls:
for j in range(1,n+1):
k=i+str(j)
new_ls.append(k)
print(new_ls)
#Results:
['p1', 'p2', 'p3', 'p4', 'q1', 'q2', 'q3', 'q4']
Q35-Write a Python program to find common items in two lists.
to find the common items between two lists, we need to iterate a loop over a list and check if that item is available in the second list.
second method: in this method, we can convert the lists into sets and check the intersection between those lists.
ls1=[1,2,3,4,5,6]
ls2=[1,2,7,8,9,10]
ls3=[]
for i in ls1:
if i in ls2:
ls3.append(i)
print(ls3)
Result= [1, 2]
#OR
ls1=[1,2,3,4,5,6]
ls2=[1,2,7,8,9,10]
set1=set(ls1)
set2=set(ls2)
common=set1.intersection(set2)
print(common)
Result= {1, 2}
#OR
ls1=[1,2,3,4,5,6]
ls2=[1,2,7,8,9,10]
print(set(ls1) & set(ls2)) #convert list into set and print items which are common in set1 & set2.
Result= {1, 2}
Q36-Write a Python program to change the position of every n-th value to the (n+1)th in a list.
for example in the list: [0,1,2,3,4,5], after changing the position of every nth element with n+1 element, the list will be [1, 0, 3, 2, 5, 4].
so in this case, we need a value=1, and then 0 while iterating the loop.
so it can be achieved from the zip function.
zip(ls[1::0], ls[0:1]) ==> it will generate the tuple from the single iteration like- (1, 0) (3, 2) (5, 4), and again we can apply the inner loop to take values from each tuple.
ls=[0,1,2,3,4,5]
new_ls=[]
for i in zip(ls[1::2],ls[0::2]):
for j in i:
new_ls.append(j)
print(new_ls)
#Result
[1, 0, 3, 2, 5, 4]
Q37- Write a Python program to convert a list of multiple integers into a single integer.
so in this program, we need to convert the list of multiple integers and print it as a single integer.
First Method: it can be done by running a loop over a list, converting each item in the string, concatenating that item into an empty string, and finally making that string an integer.
ls= [11, 33, 50]
st=""
for i in ls:
i=str(i)
st=st+i
st=int(st)
print(st)
Result= 113350
Second Method: using the join method of the string we can join the list of multiple strings as below and convert it into an integer.
NOTE: join method works on a string so again we need to make each item string.
for making all the items of the list as strings, we can use the map() function.
ls= [11, 33, 50]
ls_str=map(str,ls)
print(list(ls_str))
Result = ['11', '33', '50']
ls= [11, 33, 50]
ls_str=list(map(str,ls))
new_str="".join(ls_str)
print(int(new_str))
Result=113350
Q38- Write a Python program to split a list based on the first character of a word.
Understand: we need to split the list or we need to print the output from the given list, in such a way that the first character of each word should be checked and the corresponding word should be printed in the output?
for example, given list
word = ['be','have','do','say','get','make','go','know','take','see','come','think', 'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
now if you see the first word as be, we need to check that all words start with be should be printed in the output.
for doing this, we should have a range of alphabet (a-z), over which we can iterate a loop and check all the words that start from that particular alphabet and should be printed.
for getting the range of alphabets, we will use a string module and ascii_lowercase method as below.
import string
alphabet_range=string.ascii_lowercase
print(list(alphabet_range))
Result= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Now we can use the above range in our program and iterate an inner loop to check which all items match the alphabet and print those.
before that, we will sort our given list so that all the item of the particular alphabet is covered.
Final Program:
word = ['be','have','do','say','get','make','go','know','take','see','come','think',
'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
word_list=sorted(word)
import string
alphabet_range = list(string.ascii_lowercase)
for i in word_list:
for j in alphabet_range:
if i.startswith(j):
print(f"{i} is based on its first character - {j}")
else:
pass
Result:
ask is based on its first character - a
be is based on its first character - b
call is based on its first character - c
like this, you will get the result.
Q39- Write a Python program to create multiple empty lists.
although this question is not used that much.
we can create multiple empty lists by iterating a loop over a range.
d={}
k=d.keys()
for i in range(1,10):
if i not in k:
d[i]=[]
else:
pass
print(d)
Result= {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
Q40- Write a Python program to find missing and additional values in two lists.
for example below are the two lists in which we need to find the missing and additional values.
list1=['a','b','c','d','e'] list2=['a','b','c','f','g']
Missing values in list2 are ['d', 'e']
additional values in list2 are ['f', 'g']
list1=['a','b','c','d','e']
list2=['a','b','c','f','g']
list3=[]
for i in list1:
if i not in list2:
list3.append(i)
print(f"Missing values in list2 are {list3}")
list3.clear()
for i in list2:
if i not in list1:
list3.append(i)
print(f"addintional values in list2 are {list3}")
OR
list1=['a','b','c','d','e']
list2=['a','b','c','f','g']
set1=set(list1)
set2=set(list2)
print(set1.difference(set2))
print(set2.difference(set1))