Q-1.Write a Python program to generate all sublists of a List.
Input:[4,5,6]
Output:[[], [4], [4, 5], [4, 5, 6], [5], [5, 6], [6]]

Python Code:

#sublists of list

def sub_list(lst1):
    sublist=[[]]
    n=len(list1)
    for i in range(n+1):
        for j in range(i+1,n+1):
            sub=lst1[i:j]
            sublist.append(sub)
    return sublist
print(sub_list([4,5,6]))
Q-2.Write a python program to find the index of element in List.
Input:[5,4,3,6,8]
Output:enter key:3 index is 2

Python Code:

#find index of element in list

num=[5,4,3,6,8]
n=len(num)
key=int(input("enter key:"))
if key==num[i]:
    print("index is",i)
else:
    print("element does not exist")
    
Q-3.Write a Python program to generate all permutations of a list in Python.
Input:[1,2,3]
Output:[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2]

Python Code:

# Function to print permutations of list 
def perm_list(List): 
    return List 

# This function takes three parameters: 
#  num is list of element
#  'l' is Starting index of the list 
#  'r' is Ending index of the list. 

def permute(num, l, r): 
    if l==r: 
        print(perm_list(num))
    else: 
        for i in range(l,r+1): 
            num[l], num[i] = num[i], num[l] 
            permute(num, l+1, r) 
            num[l], num[i] = num[i], num[l]      # backtrack 
  
# Driver program to test the above function 
num = [1,2,3]
n = len(num)  
permute(num, 0, n-1) 
  
Q-4.Write a python program to sort the element in List.
Input:[16,23,43,1,31,8]
Output:Sorted array: [1, 8, 16, 23, 31, 43]

Python Code:

#sort the elements of list

def sort_list(num_list):
    for i in range(1, len(num_list)):       
        #current number to be compared
        curNum = num_list[i]
        #compare curNum with the sorted part of the array and insert curNum
        while i>0 and num_list[i-1] > curNum:
            num_list[i] = num_list[i-1]
            i = i-1
            num_list[i] = curNum
    return num_list
num_list=[16,23,43,1,31,8]
sort_list(num_list)

print('Sorted array:',sort_list(num_list))
  
Q-5.Write a python program to find even or odd item in List.
Input:[10, 21, 4, 45, 66, 93]
Output:even numbers: [10, 4, 66] odd numbers: [21, 45, 93]

Python Code:

#find odd or even element in list

list1 = [10, 21, 4, 45, 66, 93]
even_num=[]
odd_num=[]
# iterating each number in list 
for num in list1: 
      if num % 2 != 0: 
        odd_num.append(num)
     else:
        even_num.append(num)
print("even numbers:",even_num)
print("odd numbers:",odd_num)
  

Categories: Miscellaneous

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert