Python Basic Lists Programs



1)Program to check if the Given List is in Ascending Order or Not

Code:
l1= [1,2,3,5,4,6,7,8,9,10]
temp_l1 = l1[:]

# To sort the l1 list.
l1.sort()

if temp_l1==l1:
    print("List is in Ascending Order")
else:
    print("List is not an Ascending Order")


2)Program to Find Even Numbers From a List

Code:
l1= [1,2,3,5,4,6,7,8,9,10]

for i in l1:
    if i%2==0:
        print(i,end=" ")


3)Program to Merge Two Lists

Code:
l1=[1,2,3,4,5]
l2=[6,7,8,9,10]

#To append elements from another list to the current list, use the extend() method
l1.extend(l2)
print(l1)


4)Interchange First and Last Element of a List

Code:
l1= [1,2,3,5,4,6,7,8,9,10]

#Swap List 1st and Last Element
l1[0],l1[-1] = l1[-1],l1[0]

print(l1)


5)Program to Subtract a List from Another List

Code:
l1= [1,2,3,5,4,6,7,8,9,10]
l2= [5,6,7,8,9]

l3=[]

for i in l1:
    if i not in l2:
        l3.append(i)

print(l3)


6)Program to Get Data Items From a List Appearing Odd Number of Times

Code:
l1= [1,2,3,5,1,4,6,7,8,9,10,1,4,5,6,7,7,4,7,9,7,4,6]
l2=[]
for i in l1:
    if l1.count(i)%2 !=0:
        if i not in l2:
            l2.append(i)
print(l2)


7) Add a new pair of key (e.g. c ) and value (e.g. 3 ) to the dictionary and print out the new dictionary.

 d = {"a": 1, "b": 2}


Code:

d = {"a": 1, "b": 2}
print("Old Dictionary: ",d)
d["c"]=3
print("New Dictionary: ",d)

Output:

Old Dictionary:  {'a': 1, 'b': 2}
New Dictionary:  {'a': 1, 'b': 2, 'c': 3}


8) Complete the script so that it prints out the letter i using negative indexing.


         letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]


Code:

letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i","j"]
a = letters[-2]
print("Letter :",a)

Output:

Letter : i

9) Complete the script so that it removes duplicate items from the list a.
 
            a = ["1", 1, "1", 2]

Code:
a = ["1", 1, "1", 2]
a = list(set(a))
print("Updated List:",a)
Output:
Updated List: [1, 2, '1']

Checkout More Python Programs - Click Here
AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page