Python List Programs with Solution

 Python  List Programs with Solution



1. Python program to check the given list is in ascending order or not


list1=[1,2,3,4,5,6,7,8,9]
templist=list1[:]
list1.sort()
if templist==list1:
    print("Given list is in ascending order")
else:
          print("Given list is not in ascending order ")
          

O/P:
Given list is in ascending order


2. Python program to check the given list is in ascending order or not enter list elements through keyboard


list2=list(input("EnterList elements\t"))
templist=list2[:]
list2.sort()
if templist==list2:
    print("Given list is in ascending order")
else:
          print("Given list is not in ascending order ")


O/P:
Enter List elements     1 2 3 4 5 6
Given list is not in ascending order 


3. Merging two lists 


list4=[1,2,3,4,5]
list5=[6,7,8,9]
list4.extend(list5)
print(list4)


O/P:
[1, 2, 3, 4, 5, 6, 7, 8, 9]


4. Merging two lists


list6=list(input("Enter first list elements\t"))
list7=list(input("Enter second list elements\t"))
list6.extend(list7)
print(" The merged list is:\n",list6)


O/P:


Enter first list elements       1 2 3 4
Enter second list elements      5 6 7 8
 The merged list is:
 ['1', ' ', '2', ' ', '3', ' ', '4', '5', ' ', '6', ' ', '7', ' ', '8']


5. Python program to print even numbers in list


list3=[2,1,5,6]
print("Even numbers in list are\n")
for i in list3:
    if i%2==0:
        print(i)
        i=i+1 


  O/P:
Even numbers in list are
2

6


6. interchange list elements


list8=[1,2,3,4,5,6]
print("Original list\n",list8)
# 0 means first element and -1 means last element
list8[0],list8[-1]=list8[-1],list8[0]
print("Interchanged elements list\n",list8)


O/P:


Original list
 [1, 2, 3, 4, 5, 6]
Interchanged elements list
 [6, 2, 3, 4, 5, 1]


7. interchange list elements


list9=list(input("Enter list elements\t"))
print("Original list\n",list9)
# 0 means first element and -1 means last element
list9[0],list9[-1]=list9[-1],list9[0]
print("Interchanged elements list\n",list9)


O/P:
Enter list elements     1 2 3 4 5 6
Original list
 ['1', ' ', '2', ' ', '3', ' ', '4', ' ', '5', ' ', '6']
Interchanged elements list
 ['6', ' ', '2', ' ', '3', ' ', '4', ' ', '5', ' ', '1']

8. Program to subtract list from another list


A=[1,2,3,5]
B=[1,2]
C=[]
for i in A:
    if i not in B:
        C.append(i)
        print(C)

O/P:

[3]
[3, 5]
the elements which which are present in A but not in B will display
          

9. Removing a specific element from list by using its index


a=[10,20,30,40]
print("List elements\n",a)
for i in a:
    a.pop(-1)
    print(a)

O/P:

List elements
 [10, 20, 30, 40]
[10, 20, 30]
[10, 20]

टिप्पणी पोस्ट करा

0 टिप्पण्या