Simplifying 300 Python Programs on the list- Questions 41 to 50.

Simplifying 300 Python Programs on the 
                  list- Questions 41 to 50.

"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 the list.

Q41-Write a Python program to generate groups of five consecutive numbers in a list.

let's say the given list ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

to create the lists from the five consecutive numbers in a list.

from the given list to divide into 5,5 numbers, we can take step=5 of a whole range of the list.

ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
new_ls=[]
for i in range(0,len(ls),5):
  new_ls.append(ls[i:i+5])
print(new_ls)

Result: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

Q42-Write a Python program to convert a pair of values into a sorted unique array.

let's say this is the given pair of values- ls=[(1,2),(3,4),(5,6),(7,8)]

to convert it into a unique array, which means a unique list.

we need to iterate a loop over the given list of pairs, and then run the inner loop on the pair and store it into the empty list as below.

ls=[(1,2),(3,4),(5,6),(7,8)]
new_ls=[]
for i in ls:
  for j in i:
    new_ls.append(j)
print(new_ls)

OR, we can do this task by the set as well, in the set we can find the union of all the items in the list.

ls=[(1,2),(2,3),(3,4),(4,5)]
set1=set()
set2=set1.union(*ls)
print(set2)

Q43-Write a Python program to select the odd items from a list.

for selecting the odd items from the list, we can use the formula on each item to check if it does not completely divides from 2 or if the remainder is not 0 after dividing from 2.

for finding that number we can use the % symbol, which checks the reminder after dividing.

ls=[0,1,2,3,4,5,6,7,8,0,10]
new_ls=[]
for i in ls:
 if i%2!=0:
    new_ls.append(i)
print(new_ls)

Q44- Write a Python program to insert an element before each element of a list.

to insert a particular element on a particular index, we can use the index method available in the list function.

now when we use it, we need to first insert it on the 0th index position, then on the first index position 1 will be there, then on the 2nd index position we need to insert that element, and on the 3rd index, we have 3, and 4th index position we need to have particular element.

so we can see the sequence of the indexes where that particular element needs to be added is = 0,2,4,6,...n*2

let's add -a, before every element in the list.

ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(ls)):
  ls.insert(i*2,'a')
print(ls)

Q45-Write a Python program to convert a list to a list of dictionaries

for example- given list- ls = [["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]]

we need to convert lists into a dictionary, with color names and color codes as keys.

so for doing this, we need to iterate a loop over the list using the zip function.

why do we need to use the zip function here, because the zip function can give us multiple values from a single iteration?

ls = [["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]]
for color,code in zip(ls[0],ls[1]):
 print(color)
 print(code)

output:

Black
#000000
Red
#FF0000
Maroon
#800000
Yellow
#FFFF00

now we can create our program as below.

we need an empty list and dictionary, first, we will fill the values in the dictionary, and then in each iteration, we will append that complete dictionary into an empty list.

NOTE: in each iteration, we need to empty our dictionary as well so that it can have different values in the other iteration.

ls = [["Black", "Red", "Maroon", "Yellow"], ["#000000", "#FF0000", "#800000", "#FFFF00"]]
ls_dict=[]
for color,code in zip(ls[0],ls[1]):
  d={} #it is kept in the iteration, because in each iteration we need to empty it.
  d['color_name']=color #key:value
  d['color_code']=code 
  ls_dict.append(d)
print(ls_dict)

Result:

[{'color_name': 'Black', 'color_code': '#000000'}, {'color_name': 'Red', 'color_code': '#FF0000'}, {'color_name': 'Maroon', 'color_code': '#800000'}, {'color_name': 'Yellow', 'color_code': '#FFFF00'}]

flow chart: zip function gives you each value from the two items.

Q46- Write a Python program to sort a list of nested dictionaries.

in this program, we have been given a list of dictionaries and we need to sort those dictionaries by the values in the dictionaries.

for example, consider below dictionary:

my_list = [{'k1': {'subk1': 1}}, {'k1': {'subk1': 10}}, {'k1': {'subk1': 5}}]

we need to sort in such a way that, dictionary values are aligned like- 1,2,3 or a,b,c like this.

so, for doing that we can use the sort method in the list, or we can use a sorted function.

Let's use the sorted function to do that.

#sorting the values of the dictionaries, we need to use lambda function.
my_list = [{'k1': {'subk1': 1}}, {'k1': {'subk1': 10}}, {'k1': {'subk1': 5}}]
new_ls=sorted(my_list, key=lambda x:x['k1']['subk1'])
print(new_ls)

Result:

[{'k1': {'subk1': 1}}, {'k1': {'subk1': 5}}, {'k1': {'subk1': 10}}]

Q47-Write a Python program to split a list of every Nth element.

Given list=

ls=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']

let's split this by every 3rd element.

ls=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
new_ls=[ls[i] for i in range(0,len(ls),3)]
print(new_ls)

Result:

['a', 'd', 'g', 'j', 'm']

Q48- Write a Python program to compute the difference between two lists.

This Question we have already covered in my other block in Q40-

Please check this-

Question on the list- 31 to 40

Q49-Write a Python program to concatenate elements of a list.

that one also we have covered in the blog-

Question on the list- 31 to 40

ls=["red","green","black"]
for i in ls:
  st="".join(ls)
print(st)

Q50-Write a Python program to remove key-value pairs from a list of dictionaries.

consider below:

list=[{'key1':'value1', 'key2':'value2'}, {'key1':'value3', 'key2':'value4'}]

in the above list, let's say we want to remove key1 and its value.

for doing this append all other values in the empty list except the key1.

as per the below code, when you run the outer loop you will get the two dictionaries in each iteration.

so in the inner loop, every dictionary is iterated, and how to run the loop over a dictionary I have already covered in the blog.

pls, consider the below.

Running a loop in Python

list1=[{'key1':'value1', 'key2':'value2'}, {'key1':'value3', 'key2':'value4'}]
list2=[]
for i in list1:
 for key,value in i.items():
   d={}
   if key!='key1':
      d[key]=value
      list2.append(d)
print(list2)

Result:

[{'key2': 'value2'}, {'key2': 'value4'}]